javascript - setState 不更新嵌套对象

标签 javascript reactjs

在我的 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/

相关文章:

css - 以相等的 block 显示 React native ListView 项

reactjs - Material-ui:输入改变选项卡的 this.state.value

javascript - 模拟由 Redux Provider 组件封装的 React 组件函数

javascript - Reactjs img 标签未渲染 src :? 中的字符串

java - 在javascript中将JSONArray转换为String以发送到java

javascript - 实时显示所有当前访客光标

javascript - 为什么状态更新自己?不调用 setState

javascript - SlideToggle Div 动画

javascript - 将 Kendo 网格绑定(bind)到复杂数据源

javascript - Webpack & Bower : Multiple css & js files