慕桂英4014372
通常我们试图通过在一个 setState 函数中更新状态来避免多次状态调用。根据我的经验,我遇到了用当前状态更新我的状态的问题。(即不要使用this.state,尽量使用prevState)/* We could use code like the following to update specific properties */this.setState({ key1: newValue1, key3: newValue3 });你的代码sessionIncrement() {// same as decrement except does increment const toSeconds = () => { let sessionSeconds = this.state.sessionLength * 60; this.setState({ sessionSeconds: sessionSeconds }, () => console.log(this.state.sessionSeconds)); this.setState({ timeLeft: sessionSeconds}); }// Convert to MM:SS const secondsToMins = (time) => { let converted = Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2); return converted; } let time = this.state.sessionSeconds; let sessionLength = this.state.sessionLength + 1; this.setState({ sessionLength: sessionLength }, toSeconds); this.setState({ timeLeft: secondsToMins(time) }, () => console.log(this.state.timeLeft));}不确定你为什么要更新 timeLeft 两次,所以我选择用你更新它的最后一个值来更新 timeLeft。使用一个 setState:this.setState(prevState => ({ sessionLength: prevState.sessionLength+1, sessionSeconds: (prevState.sessionLength+1)*60, timeLeft: secondsToMins((prevState.sessionLength+1)*60)}), callbackFunction);有关如何使用状态的更多信息,请参阅文档。希望将所有状态更新嵌套到一个 setState 中将解决 setState 的问题,并且它是异步的。您还可以添加更多回调。this.setState({}, func1, func2, func3);or this.setState({}, () => {func1, func2, func3});