简体   繁体   English

如何防止在 React 中的功能组件中重新渲染

[英]How to prevent re-rendering in functional component in React

When I run this home page component is rendering many number of times.当我运行这个主页组件时,它会渲染很多次。 How to stop this unnecessary rendering.如何停止这种不必要的渲染。 Please help me to solve this problem.请帮我解决这个问题。 Since we dont have ShouldComponentUpdate in functional component how to handle this problem.由于我们在功能组件中没有 ShouldComponentUpdate 如何处理这个问题。 If possible send me live code example如果可能,请给我发送实时代码示例

const Home = (props) => {

  const [conversations,setConversations]=useState([]);
  const dispatch=useDispatch();
  const auth=useSelector(state=>state.auth);
  const conv=useSelector(state=>state.conversations);

  console.log(auth);
  

  useEffect(()=>{
    dispatch(getConversations(auth.user._id));
    setConversations(conv.conversations);
  },[auth,conv]);
  return(
    <>
    <Layout />
        <div className="messenger">
          <div className="chatMenu">
            <div className="chatMenuWrapper">
              <input placeholder="Search for friends" className="chatMenuInput"/>
              {
                conversations.map((c)=>{return <Conversations/>})
              }
              
            </div>
          </div>
          <div className="chatBox">
            <div className="chatBoxWrapper">
              <div className="chatBoxTop">
                <Message/>
                <Message own={true}/>
                <Message/>
                
              </div>
              <div className="chatBoxBottom">
                <textarea className="chatMessageInput" placeholder="write something"> 
                </textarea>
                <button className="chatSubmitButton">Send</button>
              </div>
            </div>
          </div>
          <div className="chatOnline">
            <div className="chatOnlineWrapper">
              <ChatOnline/>
            </div>
          </div>
        </div>
     </>
   )

 }

export default Home;

Best explanation here - https://reactjs.org/docs/hooks-reference.html#usereducer这里最好的解释 - https://reactjs.org/docs/hooks-reference.html#usereducer

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects.如果您将 State Hook 更新为与当前状态相同的值,React 将退出而不渲染子项或触发效果。 (React uses the Object.is comparison algorithm.) (React 使用 Object.is 比较算法。)

Note that React may still need to render that specific component again before bailing out.请注意,在退出之前,React 可能仍需要再次渲染该特定组件。 That shouldn't be a concern because React won't unnecessarily go “deeper” into the tree.这不应该是一个问题,因为 React 不会不必要地“深入”到树中。 If you're doing expensive calculations while rendering, you can optimize them with useMemo.如果您在渲染时进行昂贵的计算,您可以使用 useMemo 优化它们。

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

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