setState未更新状态或未重新呈现组件

时间:2020-06-08 11:39:23

标签: javascript reactjs

setState不会重新渲染组件,或者状态根本不会更新

 handleRowSelectPayrates = (status, nurseCert) => {
let { selectedCerts } = this.state
if (status) {
  selectedCerts.push(nurseCert)
} else {
  const index = selectedCerts.findIndex((s) => s.id == nurseCert.id)
  if (index > -1) {
    selectedCerts.splice(index, 1)
  }
}
console.log(selectedCerts)
this.setState({ selectedCerts})

上面是我用来设置状态的代码。我正在selectedCerificates变量中获取所需的数据,即使在那之后,我的状态也在改变。但是我希望组件能够重新渲染。

我不确定我缺少什么。此代码可在其他一些可以正常工作的地方使用。但是这里不是。

1 个答案:

答案 0 :(得分:1)

原因是,您直接在改变状态:

// you assigning state directly instead of copy of that
var  selectedCertificates  = this.state.selectedCerts; // <----- HERE

// this will update the state directly due to the above line
selectedCertificates.push(nurseCert)

// this also
selectedCerts.splice(index, 1)

更新的问题

var  {selectedCerts}  = this.state
// selectedCerts is still pointing to state array, it's still not copy of array

状态已经通过pushsplice进行了突变/更改,然后您通过this.setState分配了相同的状态,因此每个反应都没有变化(黑白状态(您已更新并传递了新值),因此不会触发重新渲染。


解决方案:

// you should pass the copy of array
var  selectedCertificates  = [...this.state.selectedCerts];