gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:47:00 25 4
gpt4 key购买 nike

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 code Backend code

最佳答案

使用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]);

希望对你有帮助

关于javascript - React Hook useEffect 缺少依赖项 : 'init' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60425780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com