search

Home  >  Q&A  >  body text

React component not re-rendering when updating state

<p>I think you have a better solution to this problem: I have a file containing an array of my cat objects: </p> <pre class="brush:php;toolbar:false;">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 } ];</pre> <p>I have: </p> <pre class="brush:php;toolbar:false;"><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></pre> <p>My filterCategory function:</p> <pre class="brush:php;toolbar:false;">filterCategory(item,index) { this.state.categories[index].selected = !this.state.categories[index].selected; this.forceUpdate(); }</pre> <p>Do you know how I can implement this without using <code>forceUpdate()</code>? I read on Stack that using <code>this.forceUpdate()</code> should be avoided. </p>
P粉277464743P粉277464743453 days ago463

reply all(2)I'll reply

  • P粉001206492

    P粉0012064922023-08-21 09:33:19

    Do not modify the status directly

    Use the setState method to change the state.

    reply
    0
  • P粉638343995

    P粉6383439952023-08-21 09:06:42

    Using setState will automatically trigger re-rendering, so do not modify the state directly, but 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 documentation:

    reply
    0
  • Cancelreply