首页 \ 问答 \ 我的所有者是否反应组件状态阻止我更新子组件状态?(Is my owner react components state preventing me from updating child component state?)

我的所有者是否反应组件状态阻止我更新子组件状态?(Is my owner react components state preventing me from updating child component state?)

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

我是否可以从子设置更新父级的状态,因此当重新打开模式时,传递的props会反映用户的更改?

我的反应结构如下:

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

它不是一对一的直接代码,只是层次结构的一种表示。

我的模态组件如下所示:

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

而Setting组件如下所示:

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

I'm trying to update the state of a checkbox within a modal that is mounted via button on the UI. I'm loading the settings when AppWrapper mounts so I can pass them around as needed. Right now i'm just passing the settings as props to SettingsList component, which then renders a series of child nodes as checkboxes. I'm able to click the checkboxes when the modal is open, and the settings successfully save to the database. However when the modal is closed and reopened the settings are refreshed to the initially set state from the owner. Refreshing the page though shows the accurately checked boxes. That makes sense to me, but i'm unsure they best way to resolve it.

Should I/Can I update the state of the parent from the child setting so when the modal is reopened that passed props reflect the user changes?

My react structure looks like this:

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

It's not direct one to one code, bust just a representation of the hierarchy.

My Modal component looks like this:

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

My SettingList component looks like this:

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

And the Setting component looks like this:

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

原文:https://stackoverflow.com/questions/39041958
更新时间:2022-04-29 20:04

最满意答案

该线

var UserData[]=new Object(); // <- wrong

不是在Javascript中初始化一个空数组的正确语法。 要创建一个数组,请执行以下操作:

var UserData = [];

使用Javascript中的数组,与其他所有内容一样,默认情况下是未定义的。 他们可以存储任何东西 要在其中存储对象,首先必须创建一个对象:

var UserDataEntry = {};

然后你可以给这个空对象分配属性:

UserDataEntry.firstname = tempUserData[0];
UserDataEntry.lastname = tempUserData[1];

然后你可以把这个新对象放入数组中:

UserData.push(UserDataEntry);

push方法将其添加为数组的最后一个元素。

或者,您可以使用JSON语法,并在创建时使用属性初始化对象:

var UserDataEntry = {
     firstname:tempUserData[0],         
     lastname:tempUserData[1],
     // ...
};

解决这个问题的更好方法是使用JSON语法将未命名的对象传递给UserData.push:

UserData.push({
     firstname:tempUserData[0],         
     lastname:tempUserData[1],
     // ...
});

The line

var UserData[]=new Object(); // <- wrong

is not the correct syntax to initialize an empty array in Javascript. To create an array, do this:

var UserData = [];

Arrays in Javascript are, just like everything else, by default untyped. They can store anything. To store an object in them, you first have to create one:

var UserDataEntry = {};

Then you can assign properties to this empty object:

UserDataEntry.firstname = tempUserData[0];
UserDataEntry.lastname = tempUserData[1];

And then you can put that new object into the array:

UserData.push(UserDataEntry);

The method push adds it as the last element of the array.

Alternatively, you can use the JSON syntax and initialize the object with the properties the moment you create it:

var UserDataEntry = {
     firstname:tempUserData[0],         
     lastname:tempUserData[1],
     // ...
};

An even more elegant way to solve this problem is to use the JSON-syntax to pass an unnamed object right to UserData.push:

UserData.push({
     firstname:tempUserData[0],         
     lastname:tempUserData[1],
     // ...
});

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。