第 66 / 105 道66 / 105 · #331
什么是 props drilling
What is props drilling
先自己答,再往下看Answer it yourself first
一句话:为了把数据送到深处的组件,中间那些根本不用它的组件被迫一层层往下传。
为什么是问题:
- 中间组件被污染—— 它的 props 签名里出现了跟它无关的字段, 可复用性下降。
- 改一处动一串—— 加一个字段要改路径上每一个组件。
- 额外重渲染—— 值变了整条路径都重渲染。
四种解法,按代价从小到大:
- 组合 /
children——最被低估的一招。 把元素直接当 props 传下去, 中间层就不用知道它需要什么数据。 - Context—— 适合主题、用户、语言这类 「整棵树都读、不常变」的值。我们那道主题切换变式题就是这个。
- 状态库—— 复杂全局状态。
- 把组件树重新拆一下—— 有时 drilling 只是拆分方式不合理的症状。
会追问:「传两三层也要上 Context 吗?」——不要。 两三层的 props 是清晰的、可追踪的; Context 会让「这个值从哪来」变得不明显, 而且 context 一变所有消费者都重渲染。「drilling 超过三四层且中间层完全无关」才值得上。
In one line: to get data down to a deep component, the components in between that have no use for it are forced to pass it along, level by level.
Why that is a problem:
- The middle components get polluted — fields that have nothing to do with them show up in their props signature, so they get less reusable.
- One change touches a whole chain — adding a field means editing every component on the path.
- Extra re-renders — when the value changes, the entire path re-renders.
Four fixes, cheapest first:
- Composition /
children— the most underrated one. Pass elements down as props and the middle layers never need to know what data they want. - Context — good for theme, user, language: values the whole tree reads and that rarely change. Our theme-switching variant question is this one.
- A state library — for complex global state.
- Re-splitting the component tree — sometimes drilling is just a symptom of a bad split.
Follow-up: “Do two or three levels need Context?” — no. Two or three levels of props are clear and easy to trace; Context makes “where did this value come from” invisible, and every consumer re-renders when the context changes. It pays off once drilling passes three or four levels and the middle layers are completely unrelated.
这道题的出处:Comes from: 课程里的这一节 →this lesson →用抽认卡过一遍Run a flashcard round