在我的 componentDidUpdate 中,我想更改嵌套对象的状态,但它不起作用。
我所做的与在 componentDidMount 和 componentWillReceiveProps 中所做的完全一样,但仍然没有任何结果。
这是我的状态:
this.state = {
timer: {
seconds: 0,
minutes: 0,
hours: 0
},
counter: 30,
intervalId : null
}
这是有效的代码:
componentDidMount() {
const intervalId = setInterval(() => {
var newTimer = { ...this.state.timer };
newTimer.seconds++;
this.setState({ timer : newTimer });
}, 100);
this.setState({
intervalId : intervalId
});
}
这是不起作用的代码:
componentDidUpdate() {
const { seconds, minutes, hours } = this.state.timer;
const { counterHit } = this.props;
const newTimer = { ...this.state.timer };
if (seconds > 0 && seconds % 30 === 0) { counterHit(); }
if (seconds >= 60) {
newTimer.minutes++;
newTimer.seconds = 0;
console.log("our new obj : ", newTimer);
console.log("Before state update: ", this.state.timer);
this.setState({ timer : newTimer }, () => {
console.log("After state update: ", this.state.timer);
});
} else if (minutes >= 60) {
newTimer.hours++;
this.setState({ timer : newTimer } );
}
}
console.log() 打印以下内容:
our new obj : {seconds: 0, minutes: 1, hours: 0}
Before state update: {seconds: 60, minutes: 0, hours: 0}
After state update: {seconds: 0, minutes: 0, hours: 0}
如您所见, session 记录没有更新。
最佳答案
问题是:
this.setState({ newTimer });
这意味着:
this.setState({
newTimer: newTimer
});
但是因为您想要更新 timer
字段,请使用以下内容:
this.setState({
timer: newTimer
});
关于javascript - setState 不更新嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52439783/