我的所有者是否反应组件状态阻止我更新子组件状态?(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
最满意答案
该线
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], // ... });
相关问答
更多-
如果source是包含所有道具的对象数组,并且您希望picked带有某些道具的对象数组,则可以使用Array.prototype.map仅使用您关注的道具来实例化新对象: var picked = source.map(function(d) { return { CVIRISK: d.CVIRISK, ERR_M_YR: d.ERR_M_YR }; }); If source is the array of objects with all the props, and you ...
-
如何正确声明对象中的Javascript对象数组(How to properly declare a Javascript array of objects in an object)[2023-10-02]
以下对我有用: function Base() { this.n = 5; this.obj = []; for (var i = 0; i < this.n; i++) { this.obj.push(new Test()); } } Test : var Test = function () {}; 看起来真正的问题是它从未创建过this.obj因为n未定义。 如果要声明数组之前的操作方式,请尝试使用new Array(this.n) 。 编辑 新的A ... -
你需要有类似下面的课程。 正如@ cricket_007所提到的,你无法从中间提取出一些东西。 Result.Java import com.fasterxml.jackson.annotation.JsonProperty; public class Result { @JsonProperty("response") public Response response; } Response.Java import com.fasterxml.jackson.annotation.J ...
-
声明一个数组是不够的。 您必须使用对象实例填充它。 aJob list[] = new aJob[lines]; aJob schedule[] = new aJob[lines]; for (int i = 0; i < lines; i++){ list[i] = new aJob(); schedule[i] = new aJob(); } Declaring an array is not enough. You must populate it with object instances. a ...
-
如何正确反序列化和遍历JSON对象的数组(How to properly deserialize and iterate over an array of JSON objects)[2022-10-14]
我可以使用什么语法来遍历此json数组,并一次打印出一个json对象? 定义一个模型: public class MyModel { public int LOCATION_ID { get; set; } public string CITY { get; set; } } 然后反序列化到这个模型: var models = JsonConvert.DeserializeObject>(stringValue); 现在你可以像使用foreach关键字一样 ... -
该线 var UserData[]=new Object(); // <- wrong 不是在Javascript中初始化一个空数组的正确语法。 要创建一个数组,请执行以下操作: var UserData = []; 使用Javascript中的数组,与其他所有内容一样,默认情况下是未定义的。 他们可以存储任何东西 要在其中存储对象,首先必须创建一个对象: var UserDataEntry = {}; 然后你可以给这个空对象分配属性: UserDataEntry.firstname = tempUs ...
-
使用这个内部对象数组(Using this inside array of objects)[2023-11-17]
表达式expanders[i].this.element意思是“查找名称为i expanders名的属性,然后在结果中查找一个名为this的属性,然后查找名为element的属性。 但是你的Expander对象没有一个叫做this的属性。 如果你想在expanders[i]访问Expander对象,那么你只需要使用它,而不是添加this. 它: expanders[i].element.addEventListener("click", function (event) { // ^--- ... -
编辑dataLayer的现有内容是不好的做法,但您只需要发送如下的覆盖属性值: dataLayer.push({'giftBatch':{'giftAmount' : 50}}); 标签管理器从最新的Object开始,并将继续向后查看以前的对象以确定每个DataLayer变量的当前设置,因此只有giftBatch.giftAmount被这个新推送覆盖。 以下是预览调试器的示例,其中显示了dataLayer的新test对象的合并视图,其中包含以前消息的属性: 解释此调试器数据层视图 在这种情况下,先前的消息 ...
-
关于排序,在原始版本中,代码不会比较students数组中的最后两个元素。 public static void sort(Student[] students) { if(students == null) return; 你的循环上限应该是students.length - 1 ,所以i的最后一个值是students.length - 2 。 // for(int i=0;i问题是内部对象中的defaultItem条目。 您的循环将在某个时刻达到此并尝试访问不存在的name ,因为没有对象。 应该可以使用is_object()轻松解决。 The problem is the defaultItem entry in your inner object. Your loop will at some point reach this and try to access name, which doesn't exist, because there is no object. S ...
相关文章
更多- [翻译][Trident] Trident state原理
- Custom SOLR Search Components - 2 Dev Tricks
- Hadoop Namenode不能启动(dfs/name is in an inconsistent state)
- Storm可靠性及事务性相关设计: Acker及Trident State
- Solr学习笔记之5、Component(组件)与Handler(处理器)学习
- 解决Hadoop namenode启动 **dfs/name is in an inconsistent state的问题
- Hadoop0.20.203.0在关机重启后,namenode启动报错(/dfs/name is in an inconsistent state)
- Hadoop下远程调试Child子进程
- Spring四种注解(@Component、@Repository、@Service、@Controller)的区别-java cms开发五
- JAVA设计模式学习23——状态模式
最新问答
更多- 获取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的基本操作命令。。。