[英]setState doesn't work when using computed property names
我正在嘗試根據傳遞給 handleTime 方法的 arguments 更新 state,所以我使用計算的屬性名稱來執行更新(使用以前的狀態)但是 setState(在 handleTime 方法中)不起作用。
這是 state:
const sessionLength = {min: 25,
sec: 0}
this.state = {
breakLength: {min: 5, sec: 0},
sessionLength: sessionLength,
sessionProcessed: sessionLength,
actualState: 'Session'
}
handleTime 方法負責更新 state 並且 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.