props vs state
props vs state
一句话:props 是父组件传进来的、只读;state 是组件自己的、可变。
| props | state | |
|---|---|---|
| 谁拥有 | 父组件 | 组件自己 |
| 能否修改 | 不能(只读) | 能,通过 setState |
| 变了会重渲染吗 | 会 | 会 |
为什么 props 必须只读?因为组件的渲染函数应该是纯的(见 #293):同样的 props 渲染出同样的 UI。 改了 props 就等于改了「输入」, 父组件下次渲染又会把它覆盖回去 —— 数据源变成两个,谁也说不清现在该信谁。
怎么判断该用哪个(实用判据):
- 能从 props 或别的 state 算出来→ 都别放,直接算(派生数据)
- 只有这个组件关心、且会变 → state
- 多个组件都要用 → 提到共同父级(#345)
- 整棵树都要用且不常变 → Context
会追问:「能把 props 存进 state 吗?」——能但通常是 bug:useState(props.value)只在首次渲染取值, 之后 props 变了 state 不会跟着变。 只有「需要一个可编辑的初始值」时才这么做, 而且要想清楚 props 变化时要不要重置。Q1 那道题的编辑功能就是这个场景, 它用 useEffect 显式同步。
In one line: props come from the parent and are read-only; state belongs to the component and can change.
| props | state | |
|---|---|---|
| Who owns it | The parent | The component itself |
| Can you change it | No (read-only) | Yes, through setState |
| Does a change re-render | Yes | Yes |
Why must props be read-only? Because a render function is supposed to be pure (see #293): the same props render the same UI. Changing props means changing the input, and the parent will overwrite it on its next render — now you have two sources of truth and nobody can say which one to trust.
How to decide which one you need — a practical test:
- You can compute it from props or other state → store neither, just compute it (derived data)
- Only this component cares, and it changes → state
- Several components need it → lift it to their common parent (#345)
- The whole tree reads it and it rarely changes → Context
Follow-up: “Can you put props into state?” — you can, and it is usually a bug: useState(props.value) reads the value on the first render only, so later prop changes never reach the state. Do it only when you need an editable initial value, and think through whether a prop change should reset it. The edit feature in the real Q1 question is that scenario — it syncs explicitly with a useEffect.