1 回答

TA貢獻1871條經驗 獲得超13個贊
通常我們試圖通過在一個 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});
添加回答
舉報