[英]React Native: Can't perform a React state update on an unmounted component
my react native application throws this error when i navigate to a specific component.当我导航到特定组件时,我的本机反应应用程序抛出此错误。 I am using functional component.
我正在使用功能组件。
This is my useEffect method.这是我的 useEffect 方法。
useEffect(() => {
let mounted = true;
if (mounted) {
getSingleProject(route.params.itemId);
console.log(singleProject && singleProject);
}
return () => {
mounted = false;
console.log("cleanup");
};
}, [getSingleProject, route.params.itemId])
I have tried another solution from other answers but i doesn't help我尝试了其他答案的另一种解决方案,但我没有帮助
This is my action method这是我的操作方法
export const getSingleProject = (id) => async (dispatch) => {
console.log("This method us called");
const config = {
headers: {
Authorization: await AsyncStorage.getItem("token"),
},
};
await axios
.get(`${API_URL}/project/single/${id}`, config)
.then((res) => {
console.log(res.data, "this is from actions");
dispatch({
type: GET_SINGLE_PROJECT,
payload: res.data,
});
})
.catch((err) => {
dispatch({
type: GET_SINGLE_PROJECT_ERROR,
payload: err,
});
});
}
This is my reducer.这是我的减速器。
export default function (state = initiastate, actions) {
const { type, payload } = actions;
case GET_SINGLE_PROJECT:
return {
...state,
singleProject: payload,
loading: false,
};
Thank you.谢谢你。
What you want to do is to prevent all the state updates if the component has been unmounted (in your case it would be dispatch
calls).如果组件已卸载(在您的情况下是
dispatch
调用),您要做的是阻止所有 state 更新。 By assigning mounted = false;
通过分配
mounted = false;
you're not achieving anything since your request is already ongoing.你没有取得任何成就,因为你的请求已经在进行中。 Instead of assigning false, in the cleanup function you need to cancel that request to prevent execution of its success/error callbacks where
dispatch
is called.而不是分配 false,在清理 function 中,您需要取消该请求以防止在调用
dispatch
时执行其成功/错误回调。
I'm not very familiar with axios
, but according to its docs you can create a cancellation token and pass it to your axios
call, so the whole solution would be something like this:我不是很熟悉
axios
,但根据其文档,您可以创建一个取消令牌并将其传递给您的axios
调用,因此整个解决方案如下所示:
useEffect(() => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
getSingleProject(route.params.itemId, source);
return () => {
source.cancel();
console.log("cleanup");
};
}, [getSingleProject, route.params.itemId])
export const getSingleProject = (id, source) => async (dispatch) => {
console.log("This method us called");
const config = {
headers: {
Authorization: await AsyncStorage.getItem("token"),
},
cancelToken: source.token
};
await axios
.get(`${API_URL}/project/single/${id}`, config)
.then((res) => {
console.log(res.data, "this is from actions");
dispatch({
type: GET_SINGLE_PROJECT,
payload: res.data,
});
})
.catch((err) => {
dispatch({
type: GET_SINGLE_PROJECT_ERROR,
payload: err,
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.