如果用户未在 componentDidMount 中登录(状态 401),我会尝试重定向到主页。
所以我尝试了
componentDidMount() {
const requestPatientListApi = async () => {
try {
const { data } = await get<AxiosResponse<PatientApi>>("/patient", { requester: "admin" });
return data.items;
} catch (err) {
//when user is not logged in redirect to "./"
props.history.push("./");
}
return [];
};
if (!axios.isCancel("")) {
// updating state when api call is not canceled
requestPatientListApi().then(patients => {
setPatients(patients);
});
}
}
componentWillUnmount() {
if (cancel) {
cancel();
}
}
但是,出现错误:
Warning: Can't perform a React state update on an unmounted component.
我尝试过使用 axios 取消 token ,但它似乎不是这种情况的解决方案。 有什么想法吗?
最佳答案
问题是您在设置状态之前进行重定向,在这种情况下,组件将不再呈现。一种方法是在异步函数中转发错误并稍后捕获它。
componentDidMount() {
const requestPatientListApi = async () => {
try {
const { data } = await get <AxiosResponse<PatientApi>>("/patient", {
requester: "admin"
});
return data.items;
} catch (err) {
throw err; // Forward the error further
}
return [];
};
if (!axios.isCancel("")) {
requestPatientListApi().then(patients => {
setPatients(patients);
}).catch(err => {
props.history.push("/"); // handle the error here
});
}
}
关于javascript - 如果用户未登录,则重定向到主页时出现内存泄漏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521015/