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.