简体   繁体   English

React hook - useEffect 缺少依赖项警告

[英]React hook - useEffect missing dependencies warning

I am not sure if this is a valid warning by using useEffect around the dependency array, it seems like whenever variable, method or dispatch inside the useEffect are giving warning that React Hook useEffect has missing dependencies: 'active', 'retrieveUser', and 'dispatch'.我不确定这是否是在依赖数组周围使用useEffect的有效警告,似乎每当useEffect中的变量、方法或调度发出警告时, React Hook useEffect 缺少依赖项:'active'、'retrieveUser' 和'派遣'。 Either include them or remove the dependency array of following example, if I just leave it as blank array to perform the componentDidMount functionality如果我只是将其保留为空白数组以执行componentDidMount功能,请包含它们或删除以下示例的依赖数组

useEffect(() => {
   setActive(active);   
   await retrieveUser(param1, param2);
   dispatch(someAction);
}, []).        // warning: React Hook useEffect has missing dependencies: 'active', 'retrieveUser', 'param1', 'param2', and 'dispatch'. Either include them or remove the dependency array, but here I just want to perform componentDidMount concept so my dependency list has to be empty

or或者

useEffect(() => {
   await retrieveUser(param1, param2);
   dispatch(someAction);
}, [userId]).   // warning: React Hook useEffect has missing dependencies: 'retrieveUser', 'param1', 'param2', and 'dispatch'. Either include them or remove the dependency array

Are those valid warning?这些是有效的警告吗? Especially that I just want to monitor on specific data field, what's the point of adding all inside dispatch or method into the dependency array if I can't add anything into the dependency list(for componentDidMOunt) or I just want to monitor userId , not param1 , param2 , etc特别是我只想监视特定的数据字段,如果我无法将任何内容添加到依赖项列表中(对于 componentDidMOunt)或者我只想监视userId ,那么将所有内部调度或方法添加到依赖项数组中的意义何在? param1param2

React is giving this warning because you are using part of your component's state or props in useEffect but have told it not to run the useEffect callback when that state/props changes. React 发出此警告是因为您正在使用组件的 state 的一部分或useEffect中的道具,但已告诉它在状态/道具更改时不要运行useEffect回调。 React assumes you will want to run that useEffect() whenever the referenced states change so it is giving you a warning. React 假设你想要在引用状态发生变化时运行那个useEffect() ,所以它会给你一个警告。 If you were only referencing variables outside of state or props, you would not get this warning.如果您仅引用 state 或道具之外的变量,您将不会收到此警告。 See below for info about conditionally running useEffect .有关有条件运行useEffect的信息,请参见下文。

Since your goal is to only run useEffect only sometimes, you're likely going to need to restructure your component so that different data is in or out of state.由于您的目标是仅在某些时候运行useEffect ,因此您可能需要重组组件,以便不同的数据进出 state。 It's difficult to recommend more specific solutions without knowing more about the component;在不了解组件的情况下很难推荐更具体的解决方案; but, a good goal is to have the state you utilize in useEffect match up with the changes that you want to trigger a rerender.但是,一个好的目标是让您在 useEffect 中使用的useEffect与您想要触发重新渲染的更改相匹配。

There might be other issues with state in your component.您的组件中的 state 可能存在其他问题。 For example, I notice that you call setActive(active);例如,我注意到您调用setActive(active); . . If active is part of the component's state, that means you are setting active to itself.如果 active 是组件 state 的一部分,则意味着您将 active 设置为自身。 Which isn't necessary.这是没有必要的。 (this is assuming you are following typical naming patterns and likely have a line at the top of your component like: (这是假设您遵循典型的命名模式并且可能在组件顶部有一行,例如:

const [active, setActive] = useState(initialValue);


Conditionally running useEffect有条件地运行useEffect

When you provide a second argument to useEffect() , it limits the situations when useEffect runs the callback function on rerenders.当您向useEffect()提供第二个参数时,它会限制 useEffect 在重新渲染时运行回调 function 的情况。 This is for performance reasons as explained in the React docs .这是出于性能原因,如React 文档中所述。

In the first useEffect where you provide an empty array, you are telling React to only run those actions ( setActive(active) ...etc.) when the component mounts and unmounts.在您提供空数组的第一个useEffect中,您告诉 React 仅在组件安装和卸载时运行这些操作( setActive(active) ...等)。

In the second useEffect where you provide an array with userId , you are telling React to only run the callback on mount, unmount, and whenever userId changes.在第二个useEffect中,你提供了一个带有userId的数组,你告诉 React 只在挂载、卸载和userId更改时运行回调。

React is giving you that warning because it knows it won't run useEffect if active ...etc or other values change. React 给你这个警告是因为它知道如果active ...etc 或其他值发生变化,它不会运行 useEffect。 This can cause different parts of your component to be referencing different states.这可能会导致组件的不同部分引用不同的状态。 For example, one part of your component might be using userId = 1 and another part is using userId = 2 .例如,您的组件的一部分可能正在使用userId = 1 ,而另一部分正在使用userId = 2 This is not how React is designed to work.这不是 React 设计的工作方式。

Create a hook that executes only once:创建一个只执行一次的钩子:

const useEffectOnce = effect => {
    useEffect(effect, []);
};

use this hook inside your component在你的组件中使用这个钩子

useEffectOnce(() => {
    const request = async () => {
        const result = await retrieveSum(param1, param2);
        setResult(result);
    };

    request();
});

Now, even if your props (param1, param2) change, the effect is called only once.现在,即使你的 props (param1, param2) 改变了,效果也只会被调用一次。 Be very careful when doing this, the component is probably buggy unless your initial props are truly special.执行此操作时要非常小心,除非您的初始道具真的很特别,否则该组件可能是错误的。 I don't see how this is different from disabling the rule with我看不出这与禁用规则有什么不同

// eslint-disable-next-line react-hooks/exhaustive-deps

Demo: https://codesandbox.io/s/trusting-satoshi-fngrw?file=/src/App.js演示: https://codesandbox.io/s/trusting-satoshi-fngrw?file=/src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM