亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React:番茄鐘:考慮到狀態的異步更新,如何正確更新狀態?

React:番茄鐘:考慮到狀態的異步更新,如何正確更新狀態?

慕桂英3389331 2023-03-24 13:55:06
在這個 React Pomodoro Clock 中,有一個函數被稱為sessionIncrement()嘗試將 state 中的一個值更新為秒,然后立即通過轉換再次更新它。但是,轉換沒有任何效果,這似乎是因為狀態的異步性質。任何幫助將不勝感激。索引.html<!DOCTYPE html><html dir="ltr"><head>  <meta charset="utf-8">  <title>25-5 Clock</title>  <style>  </style></head><body>  <main>    <div id="app"></app>    </main>  <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>  </body>  </html>
查看完整描述

1 回答

?
慕桂英4014372

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});


查看完整回答
反對 回復 2023-03-24
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號