gpt4 book ai didi

javascript - react Hook : How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule

转载 作者:行者123 更新时间:2023-11-29 18:40:24 27 4
gpt4 key购买 nike

当状态处于 Hook 状态时,它可能会变得陈旧并泄漏内存:

function App() {
const [greeting, setGreeting] = useState("hello");

const cb = useCallback(() => {
alert("greeting is " + greeting);
}, []);

return (
<div className="App">
<button onClick={() => cb()}>Click me</button>
<p>
Click the button above, and now update the greeting by clicking the one
below:
</p>
<button onClick={() => setGreeting("bye")}>
Update greeting
</button>
<p>Greeting is: {greeting}</p>
<p>
Now click the first button again and see that the callback still has the
old state.
</p>
</div>
);
}

演示:https://codesandbox.io/s/react-hook-stale-datamem-leak-demo-9pchk

问题在于,如果我们遵循 Facebook 的建议始终列出所有依赖项,并确保我们没有陈旧数据或内存泄漏(如上面的例子):

const [state, setState] = useState({
number: 0
});

const fetchRandomNumber = useCallback(async () => {
if (state.number !== 5) {
const res = await fetch('randomNumber');
setState(v => ({ ...v, number: res.number }));
}
}, [setState, state.number]);

useEffect(() => {
fetchRandomNumber();
}, [fetchRandomNumber]);

由于 Facebook 说我们应该将 fetchRandomNumber 列为依赖项(react-hooks/exhaustive-deps ESLint 规则),我们必须使用 useCallback维护一个引用,但它会在每次调用时重新生成,因为它既依赖于state.number更新它

这是一个人为的例子,但我在获取数据时遇到过很多次。在这种情况下是否有解决方法,或者 Facebook 是否有误?

最佳答案

使用状态 setter 的函数形式:

const fetchData = useCallback(async () => {
const res = await fetch(`url?page=${page}`);
setData((data) => ([...data, ...res.data]));
setPage((page) => page + 1);
}, [setData, setPage]);

现在您不需要数据和页面作为您的部门


您还可以使用 ref 仅在挂载上运行效果:

  const mounted = useRef(false);

useEffect(() => {
if(!mounted.current) {
fetchSomething();
mounted.current = true;
}

return () => { mounted.current = false }
}, [fetchSomething]);

const fetchSomething = useCallback(async () => {
...
}, [setData, setPage, data, page]);

关于javascript - react Hook : How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607239/

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