React:番茄钟:考虑到状态的异步更新,如何正确更新状态?

在这个 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>


慕桂英3389331
浏览 134回答 1
1回答

慕桂英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&nbsp; &nbsp; const toSeconds = () => {&nbsp; &nbsp; &nbsp; &nbsp; let sessionSeconds = this.state.sessionLength * 60;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ sessionSeconds: sessionSeconds }, () => console.log(this.state.sessionSeconds));&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ timeLeft: sessionSeconds});&nbsp; &nbsp; }// Convert to MM:SS&nbsp; &nbsp; const secondsToMins = (time) => {&nbsp; &nbsp; &nbsp; &nbsp; let converted = Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2);&nbsp; &nbsp; &nbsp; &nbsp; return converted;&nbsp; &nbsp; }&nbsp; &nbsp; let time = this.state.sessionSeconds;&nbsp; &nbsp; let sessionLength = this.state.sessionLength + 1;&nbsp; &nbsp; this.setState({ sessionLength: sessionLength }, toSeconds);&nbsp; &nbsp; this.setState({ timeLeft: secondsToMins(time) }, () => console.log(this.state.timeLeft));}不确定你为什么要更新 timeLeft 两次,所以我选择用你更新它的最后一个值来更新 timeLeft。使用一个 setState:this.setState(prevState => ({&nbsp; &nbsp; sessionLength: prevState.sessionLength+1,&nbsp; &nbsp; sessionSeconds: (prevState.sessionLength+1)*60,&nbsp; &nbsp; timeLeft:&nbsp; secondsToMins((prevState.sessionLength+1)*60)}), callbackFunction);有关如何使用状态的更多信息,请参阅文档。希望将所有状态更新嵌套到一个 setState 中将解决 setState 的问题,并且它是异步的。您还可以添加更多回调。this.setState({}, func1, func2, func3);or&nbsp;this.setState({}, () => {func1, func2, func3});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript