简体   繁体   English

setState不会更新嵌套对象

[英]setState doesn't update nested object

In my componentDidUpdate I want to change the state of my nested object but It doesn't work. 在我的componentDidUpdate中,我想更改嵌套对象的状态,但是它不起作用。

I did exactly as I did in componentDidMount and componentWillReceiveProps but still nothing. 我的操作与在componentDidMount和componentWillReceiveProps中所做的完全一样,但仍然没有。

Here's my state : 这是我的状态:

this.state = {
    timer: {
       seconds: 0,
       minutes: 0,
       hours: 0
    },
    counter: 30,
    intervalId : null
}

Here's the code that works : 这是有效的代码:

componentDidMount() {
    const intervalId = setInterval(() => {
        var newTimer = { ...this.state.timer };
        newTimer.seconds++;
        this.setState({ timer : newTimer });
    }, 100);
    this.setState({
        intervalId : intervalId
    });
}

Here's the code that doesn't work : 这是无效的代码:

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 } );
    }
}

The console.log()s print the following: 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}

As you can see the minutes didn't update. 如您所见,会议记录没有更新。

The issue is: 问题是:

 this.setState({ newTimer });

What that means is: 这意味着:

this.setState({ 
    newTimer: newTimer
});

But because you want to update the timer field, use this: 但是因为要更新timer字段,请使用以下命令:

this.setState({ 
    timer: newTimer
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM