React元件在更新狀態時不會重新渲染
P粉277464743
P粉277464743 2023-08-20 10:08:52
0
2
423
<p>我認為你對這個問題有更好的解決方案: 我有一個包含我的貓物件陣列的檔案:</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>我有:</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>我的filterCategory函數:</p> <pre class="brush:php;toolbar:false;">filterCategory(item,index) { this.state.categories[index].selected = !this.state.categories[index].selected; this.forceUpdate(); }</pre> <p>你知道我怎麼在不使用<code>forceUpdate()</code>的情況下實現它嗎?我在Stack上讀到應該避免使用<code>this.forceUpdate()</code>。 </p>
P粉277464743
P粉277464743

全部回覆(2)
P粉001206492

不要直接修改狀態

#

使用setState方法進行狀態變更。

P粉638343995

使用setState會自動觸發重新渲染,所以不要直接修改狀態,而是使用setState來更新狀態。

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

根據文件:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!