【问题标题】:React Hook useEffect has a missing dependency: 'props' due to one line in useEffectReact Hook useEffect 缺少依赖项:'props' 由于 useEffect 中有一行
【发布时间】:2021-12-23 09:57:09
【问题描述】:

在我的 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

【问题讨论】:

  • 您阅读警告了吗?您是否考虑过进行建议的更改?
  • 我阅读了警告。我只是不明白这个警告是什么意思。我不确定删除该道具后该怎么做。我需要在 useeffect 中使用那个道具

标签: javascript reactjs use-effect react-props react-functional-component


【解决方案1】:

你可以像这样解构你的道具:

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),但它确实有助于编写干净的代码。

【讨论】:

    猜你喜欢
    • 2020-12-29
    • 2020-11-22
    • 1970-01-01
    • 2021-02-23
    • 2020-10-26
    • 2019-10-24
    • 2020-07-24
    • 2020-03-07
    • 2020-02-25
    相关资源
    最近更新 更多