setState 不更新嵌套对象



在我的组件DidUpdate中,我想更改嵌套对象的状态,但它不起作用。

我完全按照我在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 } );
}
}

控制台.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}

如您所见,会议记录没有更新。

问题是:

this.setState({ newTimer });

这意味着:

this.setState({ 
newTimer: newTimer
});

但是,由于您要更新timer字段,请使用以下命令:

this.setState({ 
timer: newTimer
});

最新更新