状态提升是指将状态从子组件移到共同的父组件,这样多个子组件可以共享并保持与相同数据的同步。当兄弟组件需要协调时,这是标准的解决方案。
问题:兄弟组件需要共享数据
jsx
// ❌ each child has its OWN state — they can't sync
function TempInput() { [temp, setTemp] = (); ... }
如果两个兄弟组件各自持有相关状态的副本,就没有办法让它们保持一致——改变一个不会影响另一个。
function Calculator() {
const [temperature, setTemperature] = useState(0); // state LIFTED to the parent
return (
<>
{/* pass state DOWN as a prop, and a setter to update it */}
<TempInput scale="C" value={temperature} onChange={setTemperature} />
<TempInput scale="F" value={temperature} onChange={setTemperature} />
<p>Both inputs share one value: {temperature}</p>
</>
);
}
function TempInput({ value, onChange }) {
return <input value={value} onChange={e => onChange(e.target.value)} />;
}
共享状态现在存在于父组件(Calculator)中。它将值作为 prop 向下传递,并提供一个 setter,以便子组件可以请求更改(向上)。现在两个输入都反映相同的来源——编辑一个会更新两个。
1. Find the closest COMMON ancestor of the components that need to share
2. Move the state UP into that ancestor
3. Pass the value DOWN as props
4. Pass a callback DOWN so children can request updates (data up via events)
这就是"数据向下流动,事件向上传递"的流程,用于实现状态共享。
Lifting too high (state ends up far from where it's used) → prop drilling.
At that point, prefer Context or a state library instead of lifting further.
状态提升是在基于组件的框架中在兄弟组件/相关组件之间共享状态的基本技术——它在共同的父组件中保持单一的数据来源,使子组件保持同步。
在添加 Context 或 store 之前,这通常是首先考虑使用的工具。
识别何时进行提升(兄弟组件需要协调)——以及何时提升已经过度(导致 prop drilling,是时候使用 Context/store)——是很好地组织组件状态的核心。