我正在尝试使用 useEffect 钩子(Hook)。据我所知,如果 Hook 中包含依赖项数组,则只有在该特定状态发生变化时才会运行效果,但我无法让它发挥作用。每次我添加依赖项数组时,它都会无限循环。
useEffect(() => {
axiosWithAuth()
.get(`/api/parent/children/${id}`)
.then(response => {
// console.log('API response: ', response);
// console.log('childs data: ',response.data);
setData(response.data)
// console.log('new data: ', data);
});
.catch(err => console.log(err));
}, [data]);
如果我从依赖数组中提取数据,它工作正常,没有循环。前提是,如果用户单击 child 的名字,它会显示该 child 的数据(这是我正在开发的家务跟踪器),所以我会假设(我可能是错的)......
我想我可能已经自己回答了这个问题,但我想得到一些确认:
我需要为 child 设置一个状态切片,如果该状态发生变化,那么效果就会运行..所以..像这样..
const {data, setData} = useState([]);
const {child, setChild} = useState('');
useEffect(() => {
axiosWithAuth()
.get(`/api/parent/children/${id}`)
.then(response => {
// console.log('child list response: ', response);
// console.log('childs data length',response.data.length);
// console.log('childs data',response.data);
setData(response.data)
// console.log('new data: ', data);
});
.catch(err => console.log(err));
}, [child]);
我的想法是否正确,因为我需要那样做而不是按照我的方式做?
最佳答案
是的,你做得很好。 但此类问题的更好答案是:
useEffect(() => {
axiosWithAuth()
.get(`/api/parent/children/${id}`)
.then(response => {
// console.log('child list response: ', response);
// console.log('childs data length',response.data.length);
// console.log('childs data',response.data);
setData(response.data)
// console.log('new data: ', data);
});
.catch(err => console.log(err));
} , []})
当您将空数组传递给 useEffect 时,它仅运行一次
关于javascript - 对 useEffect 使用react,依赖数组仍在循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60134159/