将数组传递给 useEffect 依赖项列表 [英] Passing array to useEffect dependency list

查看:37
本文介绍了将数组传递给 useEffect 依赖项列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些数据来自每 5 秒的长轮询,我希望我的组件在每次数组的一项(或数组长度本身)发生变化时分派一个动作.将数组作为依赖项传递给 useEffect 时,如何防止 useEffect 进入无限循环,但如果任何值发生变化,仍然设法调度某些操作?

There's some data coming from long polling every 5 seconds and I would like my component to dispatch an action every time one item of an array (or the array length itself) changes. How do I prevent useEffect from getting into infinity loop when passing an array as dependency to useEffect but still manage to dispatch some action if any value changes?

useEffect(() => {
  console.log(outcomes)
}, [outcomes])

其中 outcomes 是一个 ID 数组,例如 [123, 234, 3212].数组中的项目可能会被替换或删除,因此数组的总长度可能 - 但不必 - 保持不变,因此将 outcomes.length 作为依赖项传递不是这种情况.

where outcomes is an array of IDs, like [123, 234, 3212]. The items in array might be replaced or deleted, so the total length of the array might - but don't have to - stay the same, so passing outcomes.length as dependency is not the case.

outcomes 来自 reselect 的自定义选择器:

outcomes comes from reselect's custom selector:

const getOutcomes = createSelector(
  someData,
  data => data.map(({ outcomeId }) => outcomeId)
)

推荐答案

你可以通过 JSON.stringify(outcomes) 作为依赖列表:

You can pass JSON.stringify(outcomes) as the dependency list:

阅读更多此处

useEffect(() => {
  console.log(outcomes)
}, [JSON.stringify(outcomes)])

这篇关于将数组传递给 useEffect 依赖项列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆