gpt4 book ai didi

Reactjs useMemo 钩子(Hook)行为,如 componentDidMount

转载 作者:行者123 更新时间:2023-12-04 07:44:40 25 4
gpt4 key购买 nike

我正在尝试使用 useMemo 之类的 useEffect 和 componentDidMount 行为,但我的 useMemo 的行为就像 componentWillMount 并且呈现不可阻挡。
这是代码:

useMemo(() => {
console.log('rendered');
fetch(`backend url`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userInf._id,
fields: ['readers', 'followers', 'news', 'podcast', 'video'],
}),
})
.then((res) => res.json())
.then((res) => {
setUserArticles(res.news);
})
.catch((err) => err);
}, [userArticles]);
请问有什么建议吗?

最佳答案

问题useMemo钩子(Hook)用于计算和内存一个值。看起来你的钩子(Hook)回调实际上正在更新一些状态,并且这个状态或值也在钩子(Hook)的依赖数组中声明,在更新和重新渲染之后,将再次运行钩子(Hook)回调并更新状态......创建一个无限循环。
解决方案
如果您只想在组件挂载时发出一次副作用,例如 componentDidMount ,然后使用 useEffect有一个空的依赖数组。

useEffect(() => {
console.log('rendered');
fetch(`backend url`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userInf._id,
fields: ['readers', 'followers', 'news', 'podcast', 'video'],
}),
})
.then((res) => res.json())
.then((res) => {
setUserArticles(res.news);
})
.catch((err) => err);
}, []);
Conditionally firing an effect

If you want to run an effect and clean it up only once (on mount andunmount), you can pass an empty array ([]) as a second argument. Thistells React that your effect doesn’t depend on any values from propsor state, so it never needs to re-run. This isn’t handled as a specialcase — it follows directly from how the dependencies array alwaysworks.

If you pass an empty array ([]), the props and state inside the effectwill always have their initial values. While passing [] as the secondargument is closer to the familiar componentDidMount andcomponentWillUnmount mental model, there are usually better solutionsto avoid re-running effects too often. Also, don’t forget that Reactdefers running useEffect until after the browser has painted, so doingextra work is less of a problem.

关于Reactjs useMemo 钩子(Hook)行为,如 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67263261/

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