[英]ReactJs: How to update property of state
I am trying to update the isSelected property for a row of my data stored in the state, the property doesn't update can anyone please tell me the best way to do this? 我正在尝试为状态中存储的一行数据更新isSelected属性,该属性不会更新,谁能告诉我执行此操作的最佳方法吗?
var selectedIdsPush = [];
var selectedIdsPush = this.state.contacts.slice();
for(var i=0;i<selectedIdsPush.length;i++)
{
var idAsNumber = parseInt(id);
if (page.state.contacts[i].id === idAsNumber) {
page.state.contacts[i].isSelected = true;
break;
}
}
Reacts wants consumers to setState
instead of assigning properties directly. Reacts希望使用者使用setState
而不是直接分配属性。 In this example, we could build and assign a new contacts
list using: 在此示例中,我们可以使用以下命令构建并分配新的contacts
列表:
var idAsNumber = parseInt(id);
var newContacts = this.state.contacts.map(function (contact) {
if (contact.id === idAsNumber) {
contact.isSelected = true;
}
return contact;
});
this.setState({ contacts: newContacts });
The property probably does get updated, but it won't be reflected in the UI as your app isn't re-rendered. 该属性可能确实已更新,但由于未重新呈现您的应用程序,因此不会反映在UI中。
You could call this.forceUpdate()
to force a re-render, https://facebook.github.io/react/docs/component-api.html#forceupdate . 您可以调用this.forceUpdate()
强制进行重新渲染, https: this.forceUpdate()
。
Or more likely you should use this.setState()
, https://facebook.github.io/react/docs/component-api.html#setstate . 或更可能您应该使用this.setState()
, https: this.setState()
。
I currently struggle with when/where to use state as apparently it's not advised. 我目前在何时何地使用状态方面感到困惑,因为显然不建议这样做。 Search for react avoid state
for more information. 搜索react avoid state
以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.