每次单击箭头时,React状态都会保存在本地ٍ存储中,但当您刷新页面时,由于最后一次更改不会保存到本地ٍ存储中,因此该值会减少1
如果您修改了多个项目,问题将出现在最后按下的项目中
The Code is here => https://codesandbox.io/s/solitary-currying-jb2gx?file=/src/App.js
发布于 2020-10-10 15:15:30
在使用upvote更新状态之前,您将调用序列化函数setLocalStorage()。setState函数是异步的,状态更新是由React批处理的,因此它不会立即更改。您应该在setState的第二个参数(回调)中调用setLocalStorage()。那么在调用它的时候,你就有了正确的状态。
如下所示:
upVote = (id, delta) => {
this.setState(
(e) => ({
text: e.text.map((x) =>
x.id === id ? { ...x, vote: x.vote + delta } : x
),
time: this.state.time
}),
() => this.setLocalStorage()
);
};您也可以将函数本身作为setState的第二个参数进行传递:
...
time: this.state.time
}),
this.setLocalStorage
);
}https://stackoverflow.com/questions/64290932
复制相似问题