[英]In React using nested context, how can you prevent child context from getting rerendered when the parent context is updated?
I'm using multiple context to get the data from various locations in my database.我正在使用多个上下文从我的数据库中的不同位置获取数据。
In the following code, the 'path' value passed to the provider represents the path in the database.在以下代码中,传递给提供程序的“路径”值表示数据库中的路径。 An entry in 'companys' contains a USER_NAME that refers to an entry in 'users'.
'companys' 中的条目包含引用 'users' 中的条目的 USER_NAME。 An entry in 'users' contains a 'ITEM_NAME' that refers to an entry in 'items'
“users”中的一个条目包含一个“ITEM_NAME”,它指的是“items”中的一个条目
Therefore, 'MyContext2' needs to be nested in 'MyContext1', since it gets its path from 'MyContext1'.因此,“MyContext2”需要嵌套在“MyContext1”中,因为它从“MyContext1”获取路径。 And MyContext3 is in MyContext2 similarly.
和 MyContext3 类似地在 MyContext2 中。
I have a button that when pressed updated the value 'companys/COMP_NAME/name' in the database.我有一个按钮,按下该按钮时会更新数据库中的值“companys/COMP_NAME/name”。 the problem is that this causes MyContext2 and MyContext3 to rerender, even though its values havent changed.
问题是这会导致 MyContext2 和 MyContext3 重新渲染,即使它的值没有改变。 How can I prevent this?
我怎样才能防止这种情况?
const MyComp = () => {
return (
<MyContext1.Provider value={{ path: 'companys/COMP_NAME' }}>
<MyContext1.Consumer>
{value => {
return (
<MyContext2.Provider value={{ path: `users/${value.userName}` }}>
<MyContext2.Consumer>
{value => {
return (<MyContext3.Provider value={{ path: `items/${value.itemName}` }}>
<MyContext1.Consumer>
{value => {
return (
<Button onClick={() => {
value.setData({ name: 'A Test' });
}} />
);
}}
</MyContext1.Consumer>
</MyContext3.Provider>);
}}
</MyContext2.Consumer>
</MyContext2.Provider>
);
}}
</MyContext1.Consumer>
</MyContext1.Provider>
);
};
You can check the ReactJS documentation, the PureComponent or useMemo() if you are using hooks.如果您使用钩子,您可以查看 ReactJS 文档、PureComponent 或 useMemo()。 This makes it possible not to re-render components when the state has not changed.
这使得在状态没有改变时不重新渲染组件成为可能。
https://fr.reactjs.org/docs/hooks-reference.html#usememo https://fr.reactjs.org/docs/hooks-reference.html#usememo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.