是我的所有者反应组件状态,阻止我更新子组件状态

Is my owner react components state preventing me from updating child component state?

本文关键字:状态 组件 阻止我 更新 我的 所有者      更新时间:2023-09-26

我试图在一个模态内更新一个复选框的状态,这个复选框是通过UI上的按钮安装的。当AppWrapper挂载时,我正在加载设置,以便我可以根据需要传递它们。现在我只是将设置作为道具传递给SettingsList组件,然后将一系列子节点作为复选框呈现。当模式打开时,我可以单击复选框,并将设置成功保存到数据库。但是,当模态关闭并重新打开时,设置将从所有者刷新到初始设置状态。刷新页面会显示正确的复选框。这对我来说很有意义,但我不确定这是解决问题的最佳方法。

我是否应该/可以从子设置中更新父设置的状态,以便当模态重新打开时,传递的props反映用户的更改?

我的反应结构是这样的:

<AppWrapper>
 getInitialState {settings:[]}
 <Modal>
  <SettingList settings={this.state.settings}>
   <Setting/>
  <SettingList/>
 <Modal/>
<AppWrapper/>

这不是直接的一对一代码,而只是一个层次结构的表示。

我的Modal组件是这样的:

var Modal = React.createClass({
  render: function() {
    if(this.props.isOpen){
      return (
        <ReactCSSTransitionGroup transitionName={this.props.transitionName} transitionEnterTimeout={500} transitionLeaveTimeout={500}>
        <div className="mymodal">
        {this.props.children}
        </div>
        </ReactCSSTransitionGroup>
      );
    } else {
      return <ReactCSSTransitionGroup transitionName={this.props.transitionName} transitionName={this.props.transitionName} transitionEnterTimeout={500} transitionLeaveTimeout={500} />;
    }
  }
});

我的SettingList组件是这样的:

var SettingsList = React.createClass({
  render: function() {
    var settingNodes = this.props.settings.map(function(setting, i){
      return (
        <Setting data={setting}
                  key={i}>
        </Setting>
      )
    }.bind(this));
    return (
      <div className="settings-block">
          <h2>Notifications</h2>
          <ul className="account-settings">
            {settingNodes}
          </ul>
      </div>
    )
  }
});

设置组件看起来像这样:

var Setting = React.createClass({
  saveSetting: function(one) {
    core.setAccountSettings(this.refs.setting_checkbox.id, this.refs.setting_checkbox.checked).done(function(response){
      this.setState({
        defaultChecked:  this.refs.setting_checkbox.checked
      };
      console.log(response)
    }.bind(this));
  },
  render: function() {
    //get values from settings object
    for (var k in this.props.data) {
      this.settingId = k
      this.settingName = String(k.split(/_(.+)?/)[1]).replace(/_/g, " ");
      this.settingValue = (this.props.data[k].toLowerCase() == "true")
    }
    return (
      <li className="checkbox">
      <input onChange={this.saveSetting} ref="setting_checkbox" id={this.settingId} className="settings_checkbox" type="checkbox" defaultChecked={this.settingValue}></input>
      <label htmlFor={this.settingName}>{this.settingName}</label>
      </li>
    )
  }
});

如上所述,有多种方法可以在组件之间传递数据。

http://andrewhfarmer.com/component-communication/

遵循关于回调的文章是我的解决方案。