获取数据后,ReactJS使用效果清理功能

发布于 2025-02-12 05:07:12 字数 1040 浏览 0 评论 0原文

我已经阅读了使用使用效率的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东京女 2025-02-19 05:07:12

这可以通过多种方式处理。

  • 您可以将MOTATEDTODOS作为组件外的全局变量。

  • 您可以定义mottedtodos将其传递给getTodos函数。

但是,我建议您使用

const getTodos = async (signal) => {        
    try {
        const response = await fetch(/*url*/, { signal });
            const todos = await response.json();
            if(!signal.aborted) {
                setTodos(todos);
            }
        }catch(e) {
            console.log(e);
        }
    }    

useEffect(() => {
   const abortController = new AbortController();
   getTodos(abortController.signal);

   return () => abortController.abort();
},[])

abortcontroller应该在useffect hook的依赖项数组中添加getTodos并避免状态更新和重新渲染的无限循环,wrap gettodos 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 to getTodos function.

However, I suggest you to use an AbortController

const getTodos = async (signal) => {        
    try {
        const response = await fetch(/*url*/, { signal });
            const todos = await response.json();
            if(!signal.aborted) {
                setTodos(todos);
            }
        }catch(e) {
            console.log(e);
        }
    }    

useEffect(() => {
   const abortController = new AbortController();
   getTodos(abortController.signal);

   return () => abortController.abort();
},[])

Note: You should add getTodos in the dependency array of the useEffect hook and to avoid infinite loop of state update and re-render, wrap getTodos in useCallback hook.

往事风中埋 2025-02-19 05:07:12

创建一个flushtodos函数,并在使用效果的返回声明中调用它,在该功能中,只需将您的Todos状态更新为空白阵列即可。

return () => {
  flushTodos();
}

另一个选项是:我希望您将托多斯用作状态,因此您可以在返回使用效率的返回声明中直接更新状态:

return () => {
  setTodos([]);
}

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.

return () => {
  flushTodos();
}

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:

return () => {
  setTodos([]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文