gpt4 book ai didi

How to prevent re-render by unnecessary state change in zustand store?(如何防止在ZUSTAND存储中因不必要的状态更改而重新渲染?)

转载 作者:bug小助手 更新时间:2023-10-25 19:37:48 27 4
gpt4 key购买 nike



In zustand store, I have two variable, let's say varA, varB.
And I have other component K that depends on only varB, not varA.
But the problem is when the varA is set as new value in zustand store, my K component is re-rendered, and it produce undesirable result. How can I prevent this?

在ZUSTAND存储中,我有两个变量,比方说,Vara,Varb。我还有其他分量K,它只依赖于Varb,而不依赖于Vara。但问题是,当在ZUSTAND存储中将VARA设置为新值时,我的K分量被重新呈现,并且产生了不希望看到的结果。我如何才能防止这种情况发生?


I tried useMemo, but it doesn't work.

我试过使用Memo,但它不起作用。


import React from 'react';
import { useStore } from './my-zustand-store';

function K() {
// I didn't even pull out varA from store.
const varB = useStore((state) => state.varB);

// Use useMemo to memoize varB
const memoizedVarB = React.useMemo(() => varB, [varB]);

console.log("re-rendering component K...");

return (
<div>
<p>Value of varB: {memoizedVarB}</p>
</div>
);
}

export default K;

The log is shown twice when I change varA.

当我更改VARA时,日志显示两次。


更多回答

which version of Zustand do you use?

您使用的是哪种版本的Zustand?

Hi, @diesel94, thank you. I use ^4.3.8.

嗨,@diesel94,谢谢你。我使用^4.3.8。

It looks like a bug. I read about the same problem on Zustand's GitHub issues in earlier versions and developers promised to fix that.. But who knows maybe it still exist.

看起来像是窃听器。我在早期版本中读到过Zustand的GitHub问题的相同问题,开发人员承诺会解决这个问题。但谁知道它可能还存在呢。

优秀答案推荐
更多回答

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com