Nid*_*mar 20 reactjs react-table use-effect
我正在使用 Effect 钩子从服务器获取数据,并将这些数据传递到反应表,在那里我使用相同的 api 调用从服务器加载下一组数据。当应用程序加载时,我收到如下警告
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
Run Code Online (Sandbox Code Playgroud)
效果挂钩:
useEffect(() => {
setPageLoading(true);
props
.dispatch(fetchCourses())
.then(() => {
setPageLoading(false);
})
.catch((error: string) => {
toast.error(error);
setPageLoading(false);
});
}, []);
Run Code Online (Sandbox Code Playgroud)
反应表页面:
<ReactTable
className="-striped -highlight"
columns={columns}
data={coursesData}
defaultPage={currentPage}
defaultPageSize={courses.perPage}
loading={isLoading}
manual={true}
onFetchData={setFilter}
/>
Run Code Online (Sandbox Code Playgroud)
设置过滤功能:
const setFilter = (pagination: any) => {
props.dispatch(updateCoursePageSize(pagination.pageSize));
props.dispatch(updateCourseCurrentPage(pagination.page + 1));
setCurrentPage(pagination.page);
setPerPage(pagination.pageSize);
setLoading(true);
props.dispatch(fetchCourses()).then(() => {
setLoading(false);
});
};
Run Code Online (Sandbox Code Playgroud)
有谁知道如何清理反应中的钩子
Nic*_*wer 39
使用 useEffect 您可以返回一个将在清理时运行的函数。所以在你的情况下,你会想要这样的东西:
useEffect(() => {
let unmounted = false;
setPageLoading(true);
props
.dispatch(fetchCourses())
.then(() => {
if (!unmounted) {
setPageLoading(false);
}
})
.catch((error: string) => {
if (!unmounted) {
toast.error(error);
setPageLoading(false);
}
});
return () => { unmounted = true };
}, []);
Run Code Online (Sandbox Code Playgroud)
编辑:如果你需要在 useEffect 之外启动一个调用,那么它仍然需要检查一个未挂载的变量来判断它是否应该跳过对 setState 的调用。未挂载的变量将由 useEffect 设置,但现在您需要通过一些障碍才能使变量在效果之外可访问。
const Example = (props) => {
const unmounted = useRef(false);
useEffect(() => {
return () => { unmounted.current = true }
}, []);
const setFilter = () => {
// ...
props.dispatch(fetchCourses()).then(() => {
if (!unmounted.current) {
setLoading(false);
}
})
}
// ...
return (
<ReactTable onFetchData={setFilter} /* other props omitted */ />
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56278 次 |
| 最近记录: |