React component not re-rendering when updating state
P粉277464743
P粉277464743 2023-08-20 10:08:52
0
2
456
<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粉277464743
P粉277464743

reply all(2)
P粉001206492

Do not modify the status directly

Use the setState method to change the state.

P粉638343995

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template