简体   繁体   English

React Hook useEffect 缺少依赖项:'init'

[英]React Hook useEffect has a missing dependency: 'init'

React Hook useEffect has a missing dependency: 'init'. React Hook useEffect 缺少依赖项:'init'。 Either include it or remove the dependency array react-hooks/exhaustive-deps包括它或删除依赖数组 react-hooks/exhaustive-deps

src/admin/apiAdmin.js 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源代码/添加产品.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 code Backend code我的前端代码后端代码

Use the useCallback hook to memoize the callback, it'll store the function in memory and only recompute it if its dependencies change [values]使用useCallback 钩子来记忆回调,它会将函数存储在内存中,只有在其依赖项发生变化时才重新计算它 [values]

// 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]);

Hope it helped希望有帮助

It's warning you because your init function is using the values variable which may change.这是警告您,因为您的init函数正在使用可能会更改的values变量。 You can avoid this message by setting your state with a callback that is giving you the previous state.您可以通过使用为您提供先前状态的回调设置您的状态来避免此消息。

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()
      }));
    }
  });
};

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

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