我在 moment.js 中设置小时时遇到问题,状态似乎需要一点延迟来解决时间,然后才能更改状态。
我的事件处理程序如下所示
handleKeyDownPickerInput(e, type) {
let input = e.target.value;
if (!input || isNaN(input)) return;
if (type === "hour") {
this.setState({
currentTime: moment(this.state.currentTime).set({ h: input })
});
}
}
最佳答案
this.setState({
currentTime: moment(this.state.currentTime).set({ h: input })
});
setState 方法异步运行,因此您不能依赖“this.state”,因为它可能无法读取当前状态。
this.setState((previousState) => ({
currentTime: moment(previousState.currentTime).set({ h: input })
})
);
请注意,setState 方法将匿名函数作为第一个参数,您可以读取之前的状态。
这就是你应该写的方式。
关于javascript - 使用 moment react setState 更改小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525497/