【发布时间】:2021-04-23 21:16:53
【问题描述】:
我正在使用 Reacts useReducer 钩子。我正在尝试增加 +1 或 -1,具体取决于按下 react 上的哪个按钮。我希望在返回值之前分配值,以便可以将值发布到数据库。当我运行代码时,它在 0-1 上增加 1,但之后它增加 2。我尝试使用 console.log 查看值更改,它只运行了一次 console.log,但运行了两次增量分配。在返回对象之前,如何在案例内只运行一次值分配。它还为每个值更改运行 POST 请求,(2次)
const reducer = (state, action) => {
switch (action.type) {
case "increment":{
state.count = state.count +1;
console.log("Inside Reducer, state.count", state.count);
postFourthButtonClick(state.count)
return { count: state.count}
}
case "decrement":{
state.count -=1;
console.log("Inside decrement part of reducer, state.count:", state.count);
postFourthButtonClick(state.count);
return {count: state.count}
}
default:
throw new Error();
}
【问题讨论】:
-
当您在返回值之前明确地为
state.count分配一个新值时,您正在改变您的状态。有关增量的实现,请参阅文档:React: useReducer
标签: javascript reactjs object switch-statement use-reducer