Skip to content

状态

一句话解释

状态是 内部数据组件 owns and 能更改 over 时间. 当状态更改, React re-渲染组件.

用大白话说

State is a component's memory. It holds data that can change — a counter value, a toggle flag, text a user typed, fetched data — and when that data changes, React automatically re-renders the component to reflect the new state.

You declare state with the useState hook: const [数量, setCount] = useState(0). The first element is the current value; the second is a setter function. You never modify state directly — always call the setter, which schedules a re-render.

State is local and private to the component. If two instances of the same component exist, each has its own independent state. To share state across components, lift it up to a common parent or use Context.

示例

jsx
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

数量 是状态. 点击 button calls setCount 使用新 值, 哪个触发 re-渲染 showing 更新数量.

常见混淆

  • 容易混淆的对象: Props

    关键区别: 状态是 内部 and 可变通过组件它自己. Props 是外部 and 读取-仅, 通过从 parent. Use 状态 for 数据组件 owns; use Props for 数据 parent controls.

相关术语

相关资源

相关课程

  • 状态

    学习如何 use useState and manage 组件状态.

解读错误信息

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

查看错误

← 返回术语表