使用计算 属性 名称时 setState 不起作用

setState doesn't work when using computed property names

我试图根据传递给 handleTime 方法的参数更新状态,所以我使用计算的 属性 名称来执行更新(使用以前的状态)但是 setState(在 handleTime 方法中) 不起作用。

这是状态:

const sessionLength = {min: 25,
      sec: 0}
    this.state = {
      breakLength: {min: 5, sec: 0},
      sessionLength: sessionLength,
      sessionProcessed: sessionLength,
      actualState: 'Session'
    }

handleTime 方法负责更新状态,play 方法是一个单击事件处理程序方法,它使用参数调用 handleTime(要更新的 属性 名称)

handleTime(str="sessionProcessed"){
    this.setState(state=>({[str]: {...state.[str], sec: state.[str].sec - 1}}));
    }
play(){
    if(typeof this.intervalId === 'undefined'){
      this.intervalId = setInterval(this.handleTime.bind(this),1000);
      this.setState({intervalId: this.intervalId});
    }
  }

JSX

render(){
    return(
      <div class="ml-5">
        <div>{this.state.actualState}</div>
        <div><strong id="session">{this.state.sessionProcessed.min}:{this.state.sessionProcessed.sec}</strong></div>
        <div><i id="play" class="fa fa-play" onClick={this.play}></i> <i id="pause" class="fa fa-pause" onClick={this.pause}></i></div>
      </div>
    )
  }
}

您无法使用点符号访问或设置计算键值,您只需使用括号符号即可。

例如

handleTime(str="sessionProcessed"){
    this.setState(state=>({[str]: {...state[str], sec: state[str].sec - 1}}));
}

我刚刚删除了 state.[str] 中的点,因为那样会引发错误,因此您很可能没有正确设置这些属性。

尝试更改这些内容,看看是否能解决问题。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors