第二个参数应该指定为`useEffect`的依赖项。

huangapple go评论66阅读模式
英文:

What should be specified as the second argument of useEffect?

问题

在指定第二个参数给 useEffect 的情况下是否有必要,比如一个永远不会改变的函数?

useEffect(
  () => {
    const dispatch(asyncTestFunction({ data }))
  },
  [data, dispatch],
);

在这种情况下,为什么我们将 dispatch 放在第二个参数中?

文档指出,不必包括诸如 useState 这样的函数。

https://ja.reactjs.org/docs/hooks-reference.html#usestate

英文:

Is there any point in specifying a second argument to useEffect, such as a function that never changes?

useEffect(
  () => {
    const dispatch(asyncTestFunction({ data }))
  },
  [data, dispatch],
);

In this case, why do we put dispatch as the second argument?

The documentation states that it is not necessary to include functions such as useState.

https://ja.reactjs.org/docs/hooks-reference.html#usestate

答案1

得分: 0

这些 [data, dispatch] 被称为依赖项而不是参数,这意味着你的 useEffect 依赖它们的变化才会被触发。

将数组 [] 留空,你的 useEffect 将只在页面加载时调用。在你的情况下,你可以只使用 [data],这样当数据改变时你的 useEffect 就会被触发。

你不需要将函数添加为依赖项,因为这可能会导致 useEffect 被无限调用。

想象一下这样的场景:“当 data 改变时,我想要 dispatch”,但如果我说“当 dispatch 改变时,我想再次 dispatch”。看看这是如何导致无限循环的。

英文:

Those [data, dispatch] are called dependencies not arguments, which means your useEffect is dependent on them changing for it to be triggered.

Leave the array [] empty, your useEffect will be called only when the page loads. In your case you can use only [data] so that when data changes your useEffect is triggered.

You don't need to add functions as dependencies because that may cause the useEffect to be called infinitely.

Think of it like this "when data changes I want to dispatch" but if I say "when dispatch changes I wanna dispatch again". See how that can cause an infinite loop.

答案2

得分: 0

你的实现可能是这样的,

const dispatch = useDispatch();

//触发作用效果将动作发送到redux存储

useEffect(
  () => {
     dispatch(asyncTestFunction({ data }))
  },
  [data, dispatch],
);

在这里,linter(eslint)是满意的,因为你将dispatch添加到deps数组中。linter无法知道dispatch引用在后续渲染中是否保持不变,即使它在存储创建后是稳定的。

英文:

Your implementation might be like this ,

const dispatch = useDispatch();

//Effect to dispatch action to redux store

useEffect(
  () => {
     dispatch(asyncTestFunction({ data }))
  },
  [data, dispatch],
);

Here the linter(eslint) is satisfied as you are adding dispatch to deps array.
The linter doesn't know whether the dispatch reference will remain the same or change in subsequent renders, even though it is stable since the store was created.

huangapple
  • 本文由 发表于 2023年2月27日 15:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定