当我运行这个主页组件时,它会渲染很多次。如何停止这种不必要的渲染。请帮我解决这个问题。由于我们在功能组件中没有 ShouldComponentUpdate 如何处理这个问题。如果可能,请给我发送实时代码示例
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;
答案 0 :(得分:1)
最好的解释 - https://reactjs.org/docs/hooks-reference.html#usereducer
如果您将 State Hook 更新为与当前状态相同的值,React 将退出而不渲染子项或触发效果。 (React 使用 Object.is 比较算法。)
请注意,在退出之前,React 可能仍需要再次渲染该特定组件。这不应该是一个问题,因为 React 不会不必要地“深入”到树中。如果您在渲染时进行昂贵的计算,您可以使用 useMemo 对其进行优化。