简体   繁体   English

防止子组件在带有备忘录的上下文提供程序下重新渲染

[英]prevent child component to re-render below context provider with memo

I am using a context provider in React to share data across several components.我在 React 中使用上下文提供程序在多个组件之间共享数据。 However since a value gets changed from one of my subcomponents, it rerenders all of my other components which partly leads to performance issues.但是,由于值从我的一个子组件中更改,它会重新呈现我的所有其他组件,这在一定程度上会导致性能问题。 So I want to prevent my child components to rerender.所以我想防止我的子组件重新渲染。 I tried using React.memo() but it's still rendering whenever I set the state of the Context Provider.我尝试使用 React.memo() 但每当我设置 Context Provider 的 state 时它仍在渲染。

const Authenticator = React.memo(() => {
  
  const [myChat, setMyChat] = useContext(ChatContext);

  console.log("rerender"); // gets called everytime on click
  return (
    <Button
      title="click me"
      onPress={() => setMyChat({ text: "hello" })}
    ></Button>
  );
});

My Context Provider looks like this:我的上下文提供程序如下所示:

const ChatProvider = ({ children }) => {
  const [myChat, setMyChat] = useState([]);

  return (
    <ChatContext.Provider value={[myChat, setMyChat]}>
      {children}
    </ChatContext.Provider>
  );
};

My App.js looks like this:我的 App.js 看起来像这样:

<ChatProvider>
  <Authenticator />
</ChatProvider>

React.Memo doesn't help since you are calling the useContext hook which will cause the component to re-render every time the value from the provider changes. React.Memo没有帮助,因为您正在调用useContext钩子,这将导致组件在每次来自提供者的值发生更改时重新呈现。 You should consider splitting your context into two separate contexts: one for the value, one for the state updater.您应该考虑将上下文拆分为两个单独的上下文:一个用于值,一个用于 state 更新程序。

const ChatProvider = ({ children }) => {
  const [myChat, setMyChat] = useState([])

  return (
    <ChatDispatchContext.Provider value={setMyChat}>
      <ChatValueContext.Provider value={myChat}>
        {children}
      </ChatValueContext.Provider>
    </ChatDispatchContext.Provider>
  )
}

Then, update your Authenticator component to the following:然后,将您的Authenticator组件更新为以下内容:

const Authenticator = React.memo(() => {
  const setMyChat = useContext(ChatDispatchContext)

  return (
    <Button
      title="click me"
      onPress={() => setMyChat({ text: "hello" })}
    ></Button>
  )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM