更新时间:2022-06-12 22:19:46
如果你没有在效果之外的任何地方使用 fetchBusinesses 方法,你可以简单地将它移动到效果中并避免警告
If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
但是,如果您在渲染之外使用 fetchBusinesses,则必须注意两件事
If however you are using fetchBusinesses outside of render, you must note two things
fetchBusinesses
在带有封闭闭包的挂载期间使用时,您没有将它作为方法传递有什么问题吗?fetchBusinesses
as a method when it's used during mount with its enclosing closure?总而言之,如果您在 useEffect
之外使用 fetchBusinesses
,您可以使用 //eslint-disable-next- 禁用规则线 react-hooks/exhaustive-deps
否则你可以移动 useEffect 内的方法
To sum it up I would say that if you are using fetchBusinesses
outside of useEffect
you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps
otherwise you can move the method inside of useEffect
要禁用规则,您可以像这样编写
To disable the rule you would write it like
useEffect(() => {
// other code
...
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])