Skip to content

状态

Managing 组件状态使用 useState, re-渲染, and difference 之间状态 and Props.

你将学到

  • 什么状态是 and 如何它 differs 从 Props
  • Using useState Hook 到添加状态到 函数组件
  • 如何状态更新触发 re-渲染
  • Functional 更新 and batched 更新 behavior

概念讲解

What Is State?

当props are external inputs passed from a parent, state is internal data that a component owns and manages. State is what makes a component interactive — it can change over time in response to user actions, network responses, or timers. When state changes, React automatically re-renders the component to reflect the new state. This is the core of React's reactive model: UI = f(状态).

The useState Hook

The useState hook is the primary way to add state to a function component. You call it with an initial value, and it returns a pair: the current state value and a function to update it. By convention, you destructure it as const [数量, setCount] = useState(0). The initial value is only used on the first render; subsequent renders ignore it. You can pass any type as the initial value: a number, string, boolean, array, or object.

Re-renders and Batching

When you call a state setter, React schedules a re-render. React batches multiple state updates within the same event handler into a single re-render for performance. This means calling setCount(1) and setCount(2) in the same handler results in one render with the final value. In React 18, batching is automatic even in promises, timeouts, and native event handlers.

Functional Updates

Because state updates can be asynchronous and batched, you should never compute the next state based on the current state variable directly. Instead, use the functional update form: setCount(prev => prev + 1). This guarantees you are working with the most recent state. This is especially important when multiple updates happen in the same handler or when the state depends on its previous value.

State for Objects and Arrays

When state holds an object or array, you must create a new reference when updating — never mutate. For objects, use the spread operator: setUser({ ...用户, name: "新" }). For arrays, use methods that return new arrays: setItems([...项, newItem]) or setItems(项.筛选(...)). React compares references to detect changes, so mutation without a new reference will not trigger a re-render.

示例代码

              import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);

  const increment = () => {
    // Functional update — always uses the latest state.
    setCount(prev => prev + step);
  };

  const reset = () => {
    setCount(0);
    setStep(1);
  };

  return (
    <div className="counter">
      <p>Count: {count}</p>
      <label>Step: <input type="number" value={step}
        onChange={e => setStep(Number(e.target.value))} /></label>
      <button onClick={increment}>+{step}</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}
            

useState 返回 [值, setter]. functional 更新表单 setCount(prev => prev + 步骤) ensures correctness 当多个更新 batch together.

动手试一试

  • JSON Formatter

    状态对象能 是复杂 — 格式它们到 inspect 结构.

  • Code Diff

    Compare 状态 shapes 之前 and 之后 refactor.

常见错误

错误写法

Using 状态变量 directly 相反的 functional 更新表单

正确做法

当下一个状态 depends on 上一个状态, use setCount(prev => prev + 1), 不 setCount(数量 + 1). functional 表单总是 uses latest 值.

错误写法

Mutating 状态对象 directly 相反的 创建新 ones

正确做法

从不做 状态.项.推送(newItem). 相反, 创建新 数组: setItems([...项, newItem]). React compares 引用到 detect 更改 — mutations 是不可见到 它.

练习 状态

17 个练习

练习 状态

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误