- Objective:
- Breadcrumb:
# 概念阐释
## 语义
React 的状态更新是异步。这意味着在某些情况下,部分代码将在状态完成更新之前运行,返回的仍然是旧值。将状态更新分组在一起可以提高应用程序的性能,但可能会导致状态值过时。因此,最佳实践是使用回调函数更新状态,以防止意外的过时值。
*需要查询更多资料*
## 语法
```
setCount(prevCount => prevCount + 1)
```
当你写 `setCount(prevCount => {...})` 时,你在告诉 React:“请使用当前的 `count` 值(我称之为 `prevCount`)来计算新的值”。
# 实例
```jsx
import React, { useState } from 'react';
export default function QuizNavBar({ questions }) {
const [questionIndex, setQuestionIndex] = useState(0);
// define event handlers
const goBack = () => { setQuestionIndex(prevQuestionIndex=>prevQuestionIndex-1)};
const goToNext = () => { setQuestionIndex(prevQuestionIndex=>prevQuestionIndex+1)};
// determine if on the first question or not
const onLastQuestion = questionIndex === questions.length - 1;
const onFirstQuestion = questionIndex === 0;
return (
<nav>
<span>Question #{questionIndex + 1}</span>
<div>
<button onClick={goBack} disabled={onFirstQuestion}>
Go Back
</button>
<button onClick={goToNext} disabled={onLastQuestion}> // disabled 属性:不再执行
Next Question
</button>
</div>
</nav>
);
}
```
# 相关内容
## `...prev`
- [[React Hooks useState 更新数组]]
- [[React Hooks useState 更新对象]]
# 参考资料
- [Set From Previous State](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-react-part-ii/modules/wdcp-22-function-components-and-hooks-a2dba9bf-fc64-4118-8656-dfdc35f9e5cc/lessons/the-state-hook/exercises/set-from-previous-state)