【问题标题】:React Hook useEffect has a missing dependency: 'init'React Hook useEffect 缺少依赖项:'init'
【发布时间】:2020-06-11 00:38:06
【问题描述】:

React Hook useEffect 缺少一个依赖项:'init'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps

src/admin/apiAdmin.js

export const getCategories = () => {
    return fetch(`${API}/categories`, {
        method: 'GET'
    })
        .then(response => {
            return response.json()
        })
        .catch(err => console.log(err))
}

src/AddProduct.js

//load categories and set form data
    const init = () => {
        getCategories().then(data => {
            if (data.error) {
                setValues({ ...values, error: data.error })
            } else {
                // console.log(data)
                setValues({
                    ...values,
                    categories: data.data,
                    formData: new FormData()
                })
            }
        })
    }
useEffect(() => {
        init();
    }, [])

My front codeBackend code

【问题讨论】:

  • 这是一个 linter 错误,而不是实际错误。忽略它。 useEffect(someFn, []); 是在 mount 上运行副作用的完美方式。

标签: javascript reactjs


【解决方案1】:

使用useCallback hook 来记忆回调,它会将函数存储在内存中,并且只有在其依赖关系发生变化时才会重新计算它[值]

// import { useCallback } from "react";
//load categories and set form data
const init = useCallback(() => {
  getCategories().then(data => {
    if (data.error) {
      setValues({ ...values, error: data.error });
    } else {
      // console.log(data)
      setValues({
        ...values,
        categories: data.data,
        formData: new FormData()
      });
    }
  });
}, [values]);

useEffect(() => {
  init();
}, [init]);

希望对你有帮助

【讨论】:

    【解决方案2】:

    这是警告您,因为您的 init 函数正在使用可能会更改的 values 变量。您可以通过使用提供先前状态的回调设置您的状态来避免此消息。

    const init = () => {
      getCategories().then(data => {
        if (data.error) {
          setValues(prev => ({ ...prev, error: data.error }));
        } else {
          // console.log(data)
          setValues(prev => ({
            ...prev,
            categories: data.data,
            formData: new FormData()
          }));
        }
      });
    };
    

    【讨论】:

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