简体   繁体   English

React hook 有一个不必要的依赖

[英]React hook has an unnecessary dependency

hello i'm getting this :你好,我得到了这个:

React Hook useCallback has an unnecessary dependency: 'product.selectedFilesVideos'. React Hook useCallback 有一个不必要的依赖:'product.selectedFilesVideos'。 Either exclude it or remove the dependency array react-hooks/exhaustive-deps排除它或删除依赖数组 react-hooks/exhaustive-deps

my state:我的状态:

const [product, setProduct] = useState({
     .......
    selectedFilesVideos: [],
     .......
  });

my function :我的功能:

  const addSelectedFilesVideos = useCallback(
    (files) => {
      setProduct((prevProduct) => {
        return { ...prevProduct, selectedFilesVideos: files };
      });
    },
    [product.selectedFilesVideos]
  );

where i use it :我在哪里使用它:

<FileManger
  addSelectedFiles={addSelectedFilesVideos}
  selectFiles={product.selectedFilesVideos}
  acceptFormat="video/*"
  videoOrPics="Drop video files here or click to upload."
/>

You pass to dependency array product.selectedFilesVideos which is not used in the function of useCallback .你传递给依赖数组product.selectedFilesVideos ,它没有在useCallback的函数中useCallback This array is used to call useCallback and update function when one of the dependency was updated.此数组用于在更新依赖项之一时调用useCallback和 update 函数。

That's why there is the React warning.这就是为什么会有 React 警告。

For more info: https://reactjs.org/docs/hooks-reference.html#usecallback更多信息: https : //reactjs.org/docs/hooks-reference.html#usecallback

You can work out the warning by removing product.selectedFilesVideos from the dependency array of the 'useCallback'.您可以通过从“useCallback”的依赖项数组中删除product.selectedFilesVideos来解决警告。 Since there is no actual dependency in this array for the callback hook, it should still work as expected and it will fix your warning.由于回调挂钩在此数组中没有实际依赖项,因此它仍应按预期工作,并且会修复您的警告。

 const addSelectedFilesVideos = useCallback(
    (files) => {
      setProduct((prevProduct) => {
        return { ...prevProduct, selectedFilesVideos: files };
      });
    },
    []
  );

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

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