简体   繁体   中英

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?

        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. In this example, we could build and assign a new contacts list using:

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.

You could call this.forceUpdate() to force a re-render, https://facebook.github.io/react/docs/component-api.html#forceupdate .

Or more likely you should use this.setState() , https://facebook.github.io/react/docs/component-api.html#setstate .

I currently struggle with when/where to use state as apparently it's not advised. Search for react avoid state for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM