简体   繁体   中英

React component doesn't re-render on updating state

I think u know better solution for this: I have file with array of objects with my cats:

var categories = [
  {
    "id": 1,
    "name" : "Faktury",
    "selected" : false
  },
  {
    "id": 2,
    "name" : "Telefony",
    "selected" : false
  },
  {
    "id": 3,
    "name" : "Komputery",
    "selected" : false
  },
  {
    "id": 4,
    "name" : "Rachunkowośc",
    "selected" : false
  },
  {
    "id": 5,
    "name" : "Finanse",
    "selected" : false
  }
];

and i have:

<ul className="category">
  {this.state.categories.map((item,index) =>
    <li onClick={()=>this.filterCategory(item,index)} key={item.id} className={item.selected? 'active' : ''}>{item.name}</li>
  )}
</ul>

and my filterCategory:

filterCategory(item,index) {
  this.state.categories[index].selected = !this.state.categories[index].selected;
  this.forceUpdate();
}

Do u know how i can make it without forceUpdate() ? I have read on stack i should avoid use this.forceUpdate()

Using setState automatically triggers a rerender, so instead of directly mutating the state use setState to update the state.

filterCategory(item,index){
   var categories = [...this.state.categories];
   categories[index].selected = !categories[index].selected;
   this.setState({categories})
}

According to the DOCS:

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Do Not Modify State Directly

Use setState method for state changes.

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