let [remarr, setRemarr] = useState<any[]>([])
useEffect(() => {
recommendlist(count).then((ok) => {
console.log(ok, count);
setRemarr([...remarr, ...ok.data.data])
});
}, [])
这里的问题是,在useEffect
回调中引用remarr
状态,从而使其成为依赖项。但是不能无条件地更新任何依赖项的值,因为这会导致在将remarr
状态添加为依赖项时看到的渲染循环。
WARNING in [eslint]
src\components\recommend\Index.tsx
Line 50:8: React Hook useEffect has a missing dependency: 'remarr'. Either include
it or remove the dependency array.
You can also do a functional update 'setRemarr(r => ...)' if you only need 'remarr'
in the 'setRemarr' call react-hooks/exhaustive-deps
webpack compiled with 1 warning
参考方法https://www.5axxw.com/questions/content/ef44g9
应该在状态更新程序上使用函数状态更新,以便删除外部remarr
依赖项。函数更新将状态更新排队,并将上一个状态值传递给可用于计算下一个状态值的回调。
recommendlist(count).then((ok) => {
console.log(ok, count);
setRemarr(remarr => [...remarr, ...ok.data.data])
});