簡體   English   中英

反應上下文更新不重新渲染組件

[英]react context update not re-rendering component

根據上下文提供者的反應文檔

每當 Provider 的 value 屬性發生變化時,所有作為 Provider 后代的消費者都會重新渲染。

我正在嘗試從兄弟組件 (B) 更新上下文值並從兄弟組件 (A) 讀取該更新。

這是我嘗試的一個簡單示例:

import { useState, useContext, createContext } from "react";

export const AnalyseCtx = createContext({ greeting: "hello" });

export default function App() {
  const [context, setContext] = useState({ greeting: "hello" });

  console.log("rendering App");

  return (
    <div className="App">
      <AnalyseCtx.Provider value={{ context, setContext }}>
        <ComponentA />
        <ComponentB />
      </AnalyseCtx.Provider>
    </div>
  );
}

function ComponentA() {
  const analyseContext = useContext(AnalyseCtx);
  console.log("rendering ComponentA");
  return (
    <h4>I display the context value: {analyseContext.context.greeting}</h4>
  );
}

function ComponentB() {
  console.log("rendering ComponentB");
  const analyseContext = useContext(AnalyseCtx);
  analyseContext.setContext((prevState) => {
    prevState.greeting = "updated greeting";
    console.log("updated greeting: ", prevState);
    return prevState;
  });

  return <h4>I update context value</h4>;
}

我還創建了一個代碼框來演示這個問題。

對不起,如果這是一個愚蠢的問題,但我已經被這個問題困擾了一整天。 謝謝!

組件 B 正在改變 state object 而不是返回新的 state ZA8CFDE6331BD59EB66AC96F8911 參考。 將之前的 state object 淺復制到新的 object 引用中並覆蓋您要更新的屬性。

另一個問題是組件 B 將上下文值更新為無意的副作用。 更新應該從useEffect鈎子完成,因此它無條件地將 state 更新排隊並為無限渲染循環創造條件。

function ComponentB() {
  const { setContext } = useContext(AnalyseCtx);

  useEffect(() => {
    setContext(state => ({
      ...state,
      greeting: "updated greeting",
    }));
  }, []);

  return <h4>I update context value</h4>;
}

編輯 react-context-update-not-re-rendering-component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM