React 组件不会在更新状态时重新渲染 [英] React component doesn't re-render on updating state

查看:69
本文介绍了React 组件不会在更新状态时重新渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想你知道更好的解决方案:我和我的猫有一个包含对象数组的文件:

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
  }
];

我有:

<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>

和我的过滤器类别:

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

你知道我如何在没有 forceUpdate() 的情况下做到这一点吗?我读过堆栈我应该避免使用 this.forceUpdate()

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

推荐答案

使用 setState 会自动触发重新渲染,因此不是直接改变状态,而是使用 setState 来更新状态.

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})
}

根据 DOCS:

永远不要直接改变 this.state,因为之后调用 setState() 可能替换您所做的突变.把 this.state 当作是不可变.

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

这篇关于React 组件不会在更新状态时重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆