gpt4 book ai didi

javascript - 为什么 React.StrictMode 会中断计算 props/state 的差异?

转载 作者:行者123 更新时间:2023-12-05 03:26:01 24 4
gpt4 key购买 nike

function SchrödingersDiff()
{
const [count, setCount] = useState(0);
// simulate a changing state
useEffect(() =>
{
const int = window.setInterval(() => setCount(s => s + 1), 1000);
return () => window.clearInterval(int);
}, []);

const last = useRef(0);
const diff = useMemo(() =>
{
const lastValue = last.current;
last.current = count;
const diff = count - lastValue;
// console.log(diff);
return diff;
}, [count]);

// console.log(diff);
return diff;
}

为什么这个组件在 <React.StrictMode> 下运行时总是呈现“0” ?它在没有严格模式的情况下工作正常(即呈现“1”)。

我知道严格模式会渲染两次,这可以解释,但我希望 useMemo捕获它 - 它确实如此:备忘录功能中的日志每秒打印正确的“1”。即使是外面的那个。

是否有更好的方法来计算该差异?


这是我的实际 useState/useEffect/setInterval , 已经适应保留最后一个:

export function useChannel(channelName, initialData, currentOnly)
{
const socket = useSc(s => s.socket); // gets a SocketCluster socket
const [data, setData] = useState(currentOnly ? initialData : {current: initialData});

useEffect(() =>
{
if (!socket) return;

const channel = socket.subscribe(channelName);
(async () =>
{
for await (const data of channel) setData(currentOnly ? data : s => ({current: data, last: s.current}));
})();

return () => channel.unsubscribe();
}, [socket, channelName]);

return data;
}

最佳答案

您可以定义一个 useDiff 自定义钩子(Hook),它在内部保持当前值和最后一个值的状态,这样您就可以像这样从 setInterval 回调中更新这两个值:

const useDiff = () => {
const [state, setState] = useState({
current: 0,
last: 0,
});

useEffect(() => {
const interval = window.setInterval(() => {
setState((s) => ({ current: s.current + 1, last: s.current }));
}, 1000);
return () => window.clearInterval(interval);
}, []);

return state.current - state.last;
};

演示:https://stackblitz.com/edit/react-akituv

关于javascript - 为什么 React.StrictMode 会中断计算 props/state 的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71846992/

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