Correct/Incorrect 忽略一些 React useEffect 依赖警告?

Correct/Incorrect to ignore some React useEffect dependency warnings?

这是我编写的一些示例代码,运行良好:

useEffect(() => {
  if (!rolesIsLoading && rolesStatus === 200) {
    customer.roles = rolesData.roles;
  }
}, [rolesIsLoading, rolesStatus]);

我在控制台中收到此警告:

React Hook useEffect has missing dependencies: 'customer.roles' and 'rolesData.roles'. Either include them or remove the dependency array react-hooks/exhaustive-deps

问题是,代码现在工作正常,在某些情况下,当我按照指示添加此类依赖项时,我最终会遇到无限循环或其他问题。

对于遇到类似情况时如何解决此问题的任何建议,我将不胜感激。

来自 React 文档:

Conditionally firing an effect

The default behavior for effects is to fire the effect after every completed render. That way an effect is always recreated if one of its dependencies changes.

However, this may be overkill in some cases, like the subscription example from the previous section. We don’t need to create a new subscription on every update, only if the source props has changed.

To implement this, pass a second argument to useEffect that is the array of values that the effect depends on. Our updated example now looks like this:

useEffect(
 () => {
   const subscription = props.source.subscribe();
   return () => {
     subscription.unsubscribe();
   };
 },
 [props.source],
);

因此,从上面的示例中我们可以看出依赖项数组的作用是有条件地触发效果。

你收到的警告是因为你在你的效果函数中使用了一些你没有在依赖数组中提到的外部(从效果的角度来看)变量。

React 担心您可能会在未来的渲染中为这些变量获取新值,并且由于您的效果使用了它们,因此 React "default intent" 将重新 运行 使用新变量的效果值。因此您的效果将始终是最新的。

所以你需要考虑是否要重新运行你的效果if/when那些变量在未来会发生变化。

基本建议:

  • 将它们添加到依赖数组
  • 如果他们永远不变,就没有区别
  • 如果它们发生变化,请为您的效果添加一些条件,以决定您是否应该根据新变量值做某事
  • 如果它们只改变引用,而不改变值(如函数、数组、对象等),您可以使用 useCallbackuseRef 挂钩来保留 "reference" 对于第一次渲染中的那些变量,而不是在每次渲染时都获得新的引用。