什么是状态提升
What is Lifting State Up in React
一句话:两个兄弟组件要共享同一份数据时,把 state 移到它们最近的共同父级, 再通过 props 往下传、通过回调往上报。
为什么必须这样?因为 React 是单向数据流—— 数据只能往下流,兄弟之间没有通道。唯一的共享点就是共同祖先。
做法三步:① 找到最近的共同父级; ② state 搬上去; ③ 父级把「值」和「改值的函数」 分别传给两个孩子。
代价(要主动说):提得越高,中间层被迫透传的 props 越多(这就是 props drilling,#331), 而且父级重渲染会带着整棵子树重渲染。所以原则是「提到刚好够用的那一层,别更高」。
Q1 那道真题就是一个标准的状态提升:notes 放在NoteManager(父), 表单和表格都是它的孩子; 表单提交时调用父传下来的回调。
会追问:「提太高怎么办?」—— Context、组合(children)、 或者状态库。注意 Context 解决的是「传递」, 不是「共享」—— state 该放哪还是得想清楚。
In one line: when two sibling components need the same data, move the state up to their closest common parent, then pass it down through props and report back through callbacks.
Why does it have to work this way? Because React has one-way data flow — data only travels down, and siblings have no channel between them. The only shared point is a common ancestor.
Three steps: (1) find the closest common parent; (2) move the state up there; (3) have the parent hand the value and the function that changes it to each child.
The cost — bring it up yourself: the higher you lift, the more props the middle layers are forced to pass through (that is props drilling, #331), and a parent re-render drags the whole subtree with it. So the rule is: lift to the lowest layer that works, and no higher.
The real Q1 question is a textbook lift: notes lives in NoteManager (the parent), and both the form and the table are its children; on submit the form calls the callback the parent passed down.
Follow-up: “What if it is lifted too high?” — Context, composition (children), or a state library. Note that Context solves delivery, not sharing — you still have to decide where the state belongs.