英文:
React useReducer dispatch not re-rendering the component after using fetch request
问题
在这里,我通过React的useReducer来更新状态,然后删除任务。我通过fetch API发送了一个DELETE请求,并在回调函数的末尾分派了一个操作以更新状态。但是状态没有被更新。
但是当我将代码更改如下所示:
重新渲染发生了,也就是状态被更新了。有人能告诉我为什么会发生这种情况吗?
这是我的delete reducer函数。
如果有更多的信息或需要进一步的翻译,请告诉我。
英文:
Here I am updating the state through react useReducer after deleting the task. I am sending DELETE
request through fetch API
and at the end of the callback function I am dispatching an action to update the state. But the state is not updated.
const deleteTask = async (event) => {
event.preventDefault();
console.log("delete task");
await fetch("http://localhost:3001/", {
method: "DELETE",
mode: "cors",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({ _id: state.task._id }),
});
dispatch({ type: "deleteTask", task: undefined });
};
But when I change the code as follows:
const deleteTask = async (event) => {
event.preventDefault();
dispatch({ type: "deleteTask", task: undefined });
console.log("delete task");
await fetch("http://localhost:3001/", {
method: "DELETE",
mode: "cors",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({ _id: state.task._id }),
});
};
The re-render occurs i.e the state is updated. Can someone tell me why is this happening?
And this is my delete
reducer function.
else if (action.type === "deleteTask") {
return {
...state,
isEditing: !state.isEditing,
task: action.task,
};
}
答案1
得分: 2
- 这种相同的问题我也曾经遇到过。
- 在第一种情况下,在等待fetch api后派发动作,并确保从后端发送了一些res.send,因为api调用始终需要某种响应来完成api调用请求。
- 直到它收到响应之前,api调用不能完成,所以在函数中,它将卡在等待fetch api的代码行上,不会调用派发动作,因为api调用未完成。
- 所以确保在删除路由后端中有res.send。
并且尝试这样做...
let response = await fetch(//api调用//)
console.log(response)
这样你就会知道得到了什么响应。
希望这会解决问题。如果不行,请告诉我...谢谢!
英文:
- This kind of same issue I also have faced.
- In first situation, dispatch is after await fetch api and make sure
you have sent something res.send from backend because api call always
wants some response to complete api call request. - Until it will not get any response api call can't be completed so in
function, it will stuck at code of line of await fetch api and not
going to call dispatch action as api call is incompleted. - So Make sure res.send in delete route bakcend.
And also try to do this...
let response = await fetch(//api call//)
console.log(response)
so that you will get to know what is getting as response.
I hope it will work it out. let me know if not...Thank You...!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论