Javascript React上下文将始终重新呈现
如果在上下文提供程序值中声明对象,则如果提供程序重新呈现,任何上下文使用者都将始终重新呈现,因为每次提供程序重新呈现Javascript React上下文将始终重新呈现,javascript,reactjs,react-context,Javascript,Reactjs,React Context,如果在上下文提供程序值中声明对象,则如果提供程序重新呈现,任何上下文使用者都将始终重新呈现,因为每次提供程序重新呈现值中的对象时,都会重新声明 返回( {儿童} ); 好的提供者值模式 这是一个很好的模式,因为store仅在调用setStore时才会更改 //ParentComponent.js 函数ParentComponent(){ const[store,setStore]=useState({bool:false}); 返回( setStore({…store,n:{bool:!sto
值中的对象时,都会重新声明
返回(
{儿童}
);
好的提供者值
模式
这是一个很好的模式,因为store
仅在调用setStore
时才会更改
//ParentComponent.js
函数ParentComponent(){
const[store,setStore]=useState({bool:false});
返回(
setStore({…store,n:{bool:!store.n.bool}}}>
开关箱
);
}
//ContextConsumingComponent.js
函数ContextConsumingComponent(){
const store=useContext(上下文);
log('仅当在父级中单击'Switch Bool'按钮时才会运行重新渲染');
返回{JSON.stringify(context.bool)};
}
//如果道具没有改变,避免重新渲染。
导出默认的React.memo(ContextConsumingComponent);
错误的提供程序值模式
这是一种错误的模式,因为
正在侦听对封闭对象的更改,而不是存储
和设置存储
引用自身。事实上,不管怎样,我们只想真正地听store
// ParentComponent.js
function ParentComponent() {
const [store, setStore] = useState({ bool: false });
return (
<Context.Provider value={{ store, setStore }}>
<button onClick={() => setStore({ ...store, n: { bool: !store.n.bool } })}>
Switch Bool
</button>
<ContextConsumingComponent />
</Context.Provider>
);
}
我的问题的答案可能是usemo
函数应用程序(){
const[store,setStore]=useState({bool:false});
const memoized=usemo(()=>([store,setStore]),[store,setStore]);
返回(
设置存储({bool:!store.bool})}>
开关箱
);
}
// Two Providers
function ParentComponent() {
const [store, setStore] = useState({ bool: false });
return (
<Store.Provider value={store}>
<Dispatch.Provider value={setStore}>
<button onClick={() => setStore({ ...store, n: { bool: !store.n.bool } })}>
Switch Bool
</button>
<ContextConsumingComponent />
</Dispatch.Provider>
</Store.Provider>
);
}