我可以在 useEffect 中调用单独的函数吗? [英] Can I call separate function in useEffect?
问题描述
我可以在 useEffect 中调用另一个单独的函数吗?
Can I call another separate function in useEffect?
我正在调用 useEffect 中的另一个函数,但在保存文件后,它会自动将该函数添加到 useEffect 的数组参数中.
I am calling another function in useEffect but after saving the file it is automatically adding that function in array parameters of useEffect.
请参阅下面的代码以正确理解.
See the code below for proper understanding.
保存文件前:
useEffect(() => {
getData()
console.log("useEffect ran...");
}, [query]);
function getData() {
fetch(`https://jsonplaceholder.typicode.com/${query}`)
.then(response => response.json())
.then(json => setData(json));
}
保存文件后:
useEffect(() => {
getData();
console.log("useEffect ran...");
}, [getData, query]);
function getData() {
fetch(`https://jsonplaceholder.typicode.com/${query}`)
.then(response => response.json())
.then(json => setData(json));
}
它一次又一次地运行.
推荐答案
由于您在 React 组件中声明了 getData
函数,它将在每次渲染时重新创建,从而导致效果的依赖项每次渲染都会改变.这就是每次渲染都执行效果的原因.
Since you declare the getData
function inside your React component it will be re-created on each render and thus the dependencies of your effect change on each render. This is the reason why the effect is executed on each render.
为了防止这种情况,您应该在组件外部声明 getData
函数,然后传递查询.像这样:
To prevent this you should declare the getData
function outside of the component and then pass query. Like so:
function getData(query) {
return fetch(`https://jsonplaceholder.typicode.com/${query}`)
.then(response => response.json());
}
function YouComponent({ query }) {
...
useEffect(() => {
getData(query).then(setData);
console.log("useEffect ran...");
}, [query]);
...
P.S:我不确定 eslint 插件在这样做时是否会自动将 getData 添加到依赖项中,但即使这样做也不会造成伤害.
P.S: I'm not sure whether the eslint plugin will add getData to the dependencies automatically when doing it like this but even if it does so it doesn't hurt.
这篇关于我可以在 useEffect 中调用单独的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!