ReactJS:使用 setState 更改对象的 属性 的值

ReactJS: change the value of an object's property with setState

我在构造函数中有以下代码:

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

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

使用Spread Operator (ES6)

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

使用Object.assign

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

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

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