React组件在更新状态时不重新渲染
P粉277464743
P粉277464743 2023-08-20 10:08:52
[HTML讨论组]
<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;">&lt;ul className="category"&gt; {this.state.categories.map((item,index) =&gt; &lt;li onClick={()=&gt;this.filterCategory(item,index)} key={item.id} className={item.selected? 'active' : ''}&gt;{item.name}&lt;/li&gt; )} &lt;/ul&gt;</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})
}

根据文档:

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号