React Hook useEffect 缺少依赖项:'props' 由于 useEffect 中有一行

React Hook useEffect has a missing dependency: 'props' due to one line in useEffect

在我的 React 应用程序中,有一个 useEffect。这是我的代码:

useEffect(() => {
        const trimmedArray = trimArray(props.firstInputValue);
        props.setFirstFinalSetArray(trimmedArray);
        setFirstPrintArray(`{${trimmedArray.join(', ')}}`);
    }, [props.firstInputValue]);
  1. 这个useeffect用在一个功能组件中。
  2. trimArray 是函数
  3. setFirstFinalSetArray是useState设置函数。
  4. setFirstPrintArray 是当前组件中的状态。
  5. firstInputValue 是父组件中的状态。

我发现由于这条线:props.setFirstFinalSetArray(trimmedArray); 我收到此错误:React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

你可以像这样破坏你的道具:

const MyComponent = ({firstInputValue, setFirstFinalSetArray}) => {
  const [firstPrintArray, setFirstPrintArray] = useState()
  useEffect(() => {
    const trimmedArray = trimArray(firstInputValue);
    setFirstFinalSetArray(trimmedArray);
    setFirstPrintArray(`{${trimmedArray.join(', ')}}`);
  }, [firstInputValue, setFirstFinalSetArray]);

  // rest of your code
}

当我学习 React 时,我出于某种原因犹豫是否要这样做(我想我喜欢 props),但它确实有助于编写干净的代码。