【问题标题】:ReactJS: change the value of an object's property with setStateReactJS:使用 setState 更改对象属性的值
【发布时间】:2019-07-12 01:11:52
【问题描述】:

我在 costructor 中有以下代码:

this.state = {
              messageBox: { open: false, title: 'title', content: 'content', onConfirm: function() {console.log('confirm')}, onCancel: function() {console.log('cancel')} },
            };

现在我只想用 setState 更改 open 属性。我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs object constructor state setstate


    【解决方案1】:

    使用Spread Operator (ES6)

    this.setState({ messageBox: { ...this.state.messageBox, open: true } });
    

    使用Object.assign

    this.setState({ messageBox: Object.assign({}, this.state.messageBox, { open: true } ) });
    

    【讨论】:

      【解决方案2】:

      这个问题在这里得到了很好的回答:

      How to update nested state properties in React

      但 IMO 最好的答案是指出不直接支持嵌套状态是有原因的,如果可能的话应该避免。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2020-07-18
        • 2019-03-09
        • 1970-01-01
        相关资源
        最近更新 更多