1 回答

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
通常我們?cè)噲D通過(guò)在一個(gè) setState 函數(shù)中更新?tīng)顟B(tài)來(lái)避免多次狀態(tài)調(diào)用。根據(jù)我的經(jīng)驗(yàn),我遇到了用當(dāng)前狀態(tài)更新我的狀態(tài)的問(wèn)題。(即不要使用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 兩次,所以我選擇用你更新它的最后一個(gè)值來(lái)更新 timeLeft。
使用一個(gè) setState:
this.setState(prevState => ({
sessionLength: prevState.sessionLength+1,
sessionSeconds: (prevState.sessionLength+1)*60,
timeLeft: secondsToMins((prevState.sessionLength+1)*60)}), callbackFunction
);
有關(guān)如何使用狀態(tài)的更多信息,請(qǐng)參閱文檔。
希望將所有狀態(tài)更新嵌套到一個(gè) setState 中將解決 setState 的問(wèn)題,并且它是異步的。
您還可以添加更多回調(diào)。
this.setState({}, func1, func2, func3);
or
this.setState({}, () => {func1, func2, func3});
添加回答
舉報(bào)