两者都保存影响组件渲染的数据,但它们在数据的所有权和是否可以改变上有所不同。
- props 从父组件传入组件。它们是只读的 — 组件绝不能修改它们。
- state 由组件内部拥有和管理。它可以随时间而改变,改变它会触发一次重新渲染。
示例
jsx
// `step` is a PROP — given by the parent, the child only reads it.
// `count` is STATE — owned here, changes on click, causes a re-render.
function Counter({ step }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + step)}>
{count}
);
}
< step={} />
数据向下流动(父级 → 子级通过 props),变化向上流动(子级通过像 onChange 这样的回调 prop 要求父级改变某些东西)。这种单向流动就是使 React 应用可预测的原因。
为什么这很重要
- 来自上面,且组件不应该改变它 → prop。
- 组件必须随时间改变它 → state。
- 修改 props(
props.x = 1)是一个 bug — React 不会重新渲染,而且你破坏了父级的所有权。要
