获取数据后,ReactJS使用效果清理功能
我已经阅读了使用使用效率的ReactJ中的一些好实践。我的情况将我的功能分开以获取数据并在使用效果挂钩上调用它。在这种情况下,我该如何清理功能。 ?
我已经看到了类似这样的使用效率清理:
useEffect(() => {
let isActive = true;
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((data) => {
if (isActive) {
setTodo(data);
}
})
.catch((error) => console.log(error.message));
return () => {
isActive = false;
};
}, []);
从上面的示例中,fetch函数在使用效果的内部,现在,如果有类似的情况,我该如何进行清理:
const getTodos = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todos = await response.json();
if(todos) {
setTodos(todos);
}
}catch(e) {
console.log(e);
}
}
useEffect(() => {
let mountedTodos = true;
getTodos();
return () => {
mountedTodos = false;
}
},[])
I've read some good practices in reactjs using useEffect. I have a situation which I separated my function to fetch the data and call it on the useEffect hook. How could I make some cleanup functions in this situation. ?
I've seen some useEffect cleanup like these:
useEffect(() => {
let isActive = true;
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((data) => {
if (isActive) {
setTodo(data);
}
})
.catch((error) => console.log(error.message));
return () => {
isActive = false;
};
}, []);
From the example above, the fetch function is inside with useEffect, now how can I perform some cleanup if something like this situation:
const getTodos = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todos = await response.json();
if(todos) {
setTodos(todos);
}
}catch(e) {
console.log(e);
}
}
useEffect(() => {
let mountedTodos = true;
getTodos();
return () => {
mountedTodos = false;
}
},[])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以通过多种方式处理。
您可以将
MOTATEDTODOS
作为组件外的全局变量。您可以定义
mottedtodos
将其传递给getTodos
函数。但是,我建议您使用
abortcontroller应该在
useffect
hook的依赖项数组中添加getTodos
并避免状态更新和重新渲染的无限循环,wrapgettodos
usecallback hook。This could be handled in multiple ways.
You could have
mountedTodos
as a global variable outside the component.You could defined
mountedTodos
as an object and pass it togetTodos
function.However, I suggest you to use an AbortController
Note: You should add
getTodos
in the dependency array of theuseEffect
hook and to avoid infinite loop of state update and re-render, wrapgetTodos
inuseCallback
hook.创建一个flushtodos函数,并在使用效果的返回声明中调用它,在该功能中,只需将您的Todos状态更新为空白阵列即可。
另一个选项是:我希望您将托多斯用作状态,因此您可以在返回使用效率的返回声明中直接更新状态:
Create a flushTodos function and call it in return statement of useEffect and in that function just update your state of todos to blank array.
And other option is: I hope you are using todos as a state so you can directly update the state in return statement of useEffect like this: