[英]Update React Context without re-rendering the component making the update
[英]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>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.