代码:
useEffect(() => {
// ... 省略无关代码
setFriends([msg, ...friends]);
}, [])
本意是获取到msg数据后,利用原有的friends
,更新出现在的friends
数据。
然后就报警告:
React Hook useEffect has a missing dependency: 'friends'.
Either include it or remove the dependency array.
You can also do a functional update 'setFriends(f => ...)'
if you only need 'friends' in the 'setFriends' call react-hooks/exhaustive-deps
原因大致是在useEffect
中引入了friends
这个状态数据,让friends
变成了依赖数据。
这样可能会导致循环渲染的问题。就是friends
变化了,然后去通过setFriends
方法
去更新了friends
,这让friends
又发生了变化,于是继续去调用setFriends
去更新friends
…
此时,如果不想让friends
作为依赖项,就用函数的方式去删除friends
这个外部依赖,
代码改为这样:
useEffect(() => {
// ... 省略无关代码
setFriends(friends => [msg, ...friends]);
}, [])
问题解决。