【问题标题】:React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency arrayReact Hook useEffect 缺少依赖项:'props.myObj'。包含它或删除依赖数组
【发布时间】:2021-09-10 14:22:39
【问题描述】:

以下代码运行良好。每次props.myObj["test"]?.prop1?.data 更改时都会触发useEffect 的功能。 但是,我收到了警告React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency array

我不能将它包含在依赖项数组中,因为它会导致无限循环(因为props.myObj 具有不断变化的嵌套对象)。 当然,我不能删除当前的依赖项。那么知道如何解决这个问题吗?

useEffect(() => {
    const data = props.myObj["test"]?.prop1?.data || {};
    if (data["first"]) {
        setTotalData(data["first"].data.length);
    }
}, [props.myObj["test"]?.prop1?.data]);

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    如果"test" 是一个常量,则改为执行以下操作。

    const data = props.myObj.test?.prop1?.data || {};
    

    如果不是,那么你使用 useEffect 钩子错误,因为依赖列表中的变量在引用方面应该是恒定的。

    【讨论】:

    • 测试不是常数
    【解决方案2】:

    您应该禁用警告:

    useEffect(() => {
        ...
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    

    这样做仍然是一个好习惯。

    【讨论】:

      【解决方案3】:

      您需要比较上一个(上一个)totalData,如果上一个totalData(即数据["first"].data.length)与新的不同,那么只做setTotalData。否则,如果每次都改变,那么你将有无限循环。但看起来你正在根据道具计算一些价值。可以使用 useMemo 将其作为计算值。

      const totalData = React.useMemo(props.myObj?.test?.prop1?.data?.first ?  data?.first?.data?.length : 0,[props.myObj])
      

      【讨论】:

        猜你喜欢
        • 2020-09-26
        • 2021-10-29
        • 2020-07-19
        • 2020-05-31
        • 1970-01-01
        • 2021-08-24
        • 2023-04-09
        • 1970-01-01
        • 2020-11-05
        相关资源
        最近更新 更多