DrillLab
八股题库Question bank

105 道问答题,一道一卡105 questions, one card each

默认只显示问题 —— 先自己在心里答一遍,再展开对答案。答不上来就标「不会」,下次抽认卡会先抽它。Only the question shows by default. Answer it in your head first, then open the answer. Mark the ones you miss; the flashcard round puts those first.

0 / 105道自评过self-assessed
0Got it0模糊Shaky0不会No idea105还没做Not seen
正在读这台浏览器里的标记…Reading your marks from this browser…
标记不是打分,是给下一轮排队Marks are a queue, not a score

标「不会」的题会排到抽认卡最前面,标「会」的进低频池排最后。所以别客气 —— 觉得答得磕磕巴巴就标「模糊」。准备好了就去抽认卡“No idea” jumps to the front of the next round; “got it” drops to the back. So be honest — if it came out shaky, mark it shaky. Then go run a flashcard round.

题目Questions

筛出 36 道(共 105 道) · 第 1 / 3 页。36 of 105 questions · page 1 / 3.
React 与生态React & ecosystem#321

什么是 SPA

What is a SPA

看答案Show answer

一句话:单页应用 ——只加载一个 HTML, 之后的页面切换由 JS 在前端换内容, 不再向服务器请求整页。

好处:切页面没有白屏刷新、体验接近原生 App、 前后端彻底分离(后端只给 JSON)。

代价(面试重点问这半边):

  • 首屏慢—— 要先下载并执行一大包 JS 才能看到内容。 解法是代码分割(React.lazy,见 #347) 和 SSR。
  • SEO 差—— 爬虫拿到的 HTML 是空的<div id="root"></div>。 解法是 SSR / SSG(Next.js)。
  • 路由要自己管—— 前进后退、深链接、刷新后还在当前页, 都得靠 history API 和服务端的 fallback 配置。「刷新 404」就是漏配了 fallback
  • 内存泄漏风险—— 页面不刷新, 定时器和监听器不会被自动清掉。这就是 useEffect必须写清理函数的现实原因。

会追问:「MPA 什么时候更好?」—— 内容型站点(博客、文档、电商详情页), 重 SEO、首屏优先、交互不复杂的。答得出「看场景」比一味夸 SPA 好。

In one line: a single-page application — one HTML document gets loaded, and from then on JS swaps the content on the client instead of asking the server for a whole new page.

Upsides: no white flash when you change pages, it feels close to a native app, and front end and back end are fully separated (the server only returns JSON).

Costs — this is the half they probe:

  • Slow first paint — you have to download and run a big JS bundle before anything shows up. The fixes are code splitting (React.lazy, see #347) and SSR.
  • Weak SEO — a crawler receives an empty<div id="root"></div>. The fix is SSR / SSG (Next.js).
  • You own the routing — back and forward, deep links, staying on the current page after a refresh, all of it rides on the history API plus a fallback on the server. “404 on refresh” means the fallback is missing.
  • Memory leaks — the page never reloads, so timers and listeners are never cleared for you. That is the practical reason useEffect needs a cleanup function.

Follow-up: “When is an MPA better?” — content sites (blogs, docs, product detail pages) where SEO and first paint matter and the interaction stays simple. “It depends on the case” beats praising SPAs unconditionally.

React 与生态React & ecosystem#320

React 的优势是什么

React advantage

看答案Show answer

一句话:声明式 + 组件化 + 单向数据流—— 你描述「界面应该长什么样」, React 负责把 DOM 变成那样。

  • 声明式—— 你写{items.map(...)}, 不写「找到 ul、创建 li、appendChild」。省掉的是「怎么从状态 A 变到状态 B」这类过程代码, 而这正是 bug 最多的地方。
  • 组件化—— UI 拆成可复用、 可独立测试的单元。
  • 单向数据流—— props 往下、事件往上。 出问题时排查路径是确定的: 数据只可能从一个方向来。
  • 生态—— Router、 状态库、Next.js、React Native (同一套心智模型能写移动端)。

会追问缺点(一定要准备): 只是个视图库,路由和状态都要自己选,选型成本高; 性能优化要手动(memo /useMemo,React 19 之前没有自动记忆化); JSX 和 hooks 规则对新手有门槛;版本迁移的心智负担不小(class → hooks → Server Components)。

In one line: declarative + component-based + one-way data flow — you describe what the UI should look like and React makes the DOM match.

  • Declarative — you write {items.map(...)}, not “find the ul, create an li, appendChild”. What you drop is the step-by-step code for getting from state A to state B, and that is where most bugs live.
  • Components — the UI splits into reusable units you can test on their own.
  • One-way data flow — props go down, events go up. When something breaks, there is exactly one path to trace: the data can only have come from one direction.
  • Ecosystem — Router, state libraries, Next.js, React Native (the same mental model gets you a mobile app).

They will ask for the downsides (have them ready): it is only a view library, so you pick the router and the state layer yourself — the cost of those decisions is real; performance work is manual (memo / useMemo; there was no automatic memoization before React 19); JSX and the hook rules are a hurdle for beginners; and version migrations carry a lot of mental load (class → hooks → Server Components).

React 与生态React & ecosystem#319

React vs Angular

React vs Angular

看答案Show answer

一句话:React 是(只管视图,其他自己选); Angular 是框架(路由、HTTP、表单、依赖注入、 测试全都自带)。

ReactAngular
定位全套框架
语言JS / TS,JSXTypeScript 强制,HTML 模板
数据流单向支持双向绑定(ngModel
DOM 策略虚拟 DOM增量 DOM + 变更检测
学习曲线入门低,但选型多入门陡(DI、RxJS、装饰器),之后规范统一
适合灵活、迭代快、团队愿意自己搭大型企业项目、要求统一规范

怎么答得体面:别踩一捧一。说 「React 给自由也给选型负担, Angular 给约定也给学习成本;小而快的项目和需要长期多人维护的大项目, 答案不一样」。

会追问 Vue—— Vue 在两者之间:有官方路由和状态库 (比 React 统一), 但比 Angular 轻;模板语法上手快。

In one line: React is a library (it handles the view, you choose the rest); Angular is a framework (routing, HTTP, forms, dependency injection and testing all come in the box).

ReactAngular
What it isA libraryA full framework
LanguageJS / TS, JSXTypeScript required, HTML templates
Data flowOne-wayTwo-way binding available (ngModel)
DOM strategyVirtual DOMIncremental DOM + change detection
Learning curveEasy to start, but many choices to makeSteep at first (DI, RxJS, decorators), consistent after
FitsFlexible work, fast iteration, a team happy to assemble its own stackLarge enterprise projects that need one standard

How to answer without picking a fight: do not talk one down to lift the other. Say “React gives you freedom and the burden of choosing; Angular gives you conventions and a learning cost. The answer differs for a small fast project and for a big one many people maintain for years.”

They will ask about Vue — Vue sits between the two: it has an official router and state library (more unified than React) but stays lighter than Angular, and the template syntax is quick to pick up.

React 与生态React & ecosystem#326

什么是 JSX

What is JSX

看答案Show answer

一句话:JavaScript 的语法扩展, 让你在 JS 里写类似 HTML 的结构。浏览器不认识它, 要经过 Babel 编译成普通函数调用。

编译成什么(这是考点): 旧版编译成React.createElement(type, props, ...children)React 17 之后用新的 JSX 转换, 编译成 _jsx(...), 所以不用再手动import React 了。

要说清的几条规则:

  • 必须有单一根节点—— 因为函数只能返回一个值。 不想多套 div 就用Fragment(见 #338)。
  • 属性名用小驼峰——className(因为class 是 JS 关键字)、htmlForonClick
  • {} 里放表达式, 不能放语句 —— 所以条件渲染用三元或&&,不能写 if
  • JSX 默认转义, 所以天然防 XSS; 要插 HTML 得显式写dangerouslySetInnerHTML——名字故意起得难听, 就是让你警觉。

会追问:「JSX 是必须的吗?」—— 不是,你可以手写createElement, 只是没人愿意。JSX 的价值是让 「UI 结构」在代码里长得像结构

In one line: a syntax extension for JavaScript that lets you write HTML-like structure inside JS. The browser does not understand it — Babel compiles it into plain function calls.

What it compiles to (this is the part being tested): old versions produced React.createElement(type, props, ...children); since React 17 the new JSX transform emits _jsx(...), which is why you no longer have to write import React by hand.

The rules you should state clearly:

  • One root node is required — a function can only return one value. If you do not want another div, use a Fragment (see #338).
  • Attribute names are camelCase className (because class is a JS keyword), htmlFor, onClick.
  • {} holds an expression, not a statement — so conditional rendering uses a ternary or &&, never if.
  • JSX escapes by default, so you get XSS protection for free; injecting raw HTML takes an explicit dangerouslySetInnerHTML the name is deliberately ugly so that you stop and think.

Follow-up: “Is JSX mandatory?” — no, you can call createElement yourself, nobody wants to. The value of JSX is that UI structure looks like structure in the code.

JSXJSX 编译成什么示意Illustrative
1// 你写的
2const el = <button className="btn" onClick={handle}>点我</button>;
3
4// Babel 编译后(React 17 之前)
5const el = React.createElement(
6 "button",
7 { className: "btn", onClick: handle },
8 "点我",
9);
10
11// {} 里只能放表达式
12{if (ok) <A />} // ✗ 语法错误
13{ok ? <A /> : null} // ✓
14{ok && <A />} // ✓(注意 0 会被渲染出来,见 #281)
1// What you write
2const el = <button className="btn" onClick={handle}>Click me</button>;
3
4// After Babel compiles it (before React 17)
5const el = React.createElement(
6 "button",
7 { className: "btn", onClick: handle },
8 "Click me",
9);
10
11// Only an expression can go inside {}
12{if (ok) <A />} // ✗ syntax error
13{ok ? <A /> : null} // ✓
14{ok && <A />} // ✓ (careful: 0 does get rendered, see #281)
React 与生态React & ecosystem#330

虚拟 DOM 和 diff 算法

Virtual DOM and diffing algorithm

看答案Show answer

一句话:虚拟 DOM 是用普通 JS 对象描述真实 DOM 的一棵轻量树。 状态变了先在内存里生成新树, 和旧树 diff,算出最小改动,再一次性打到真实 DOM 上

为什么快 —— 说准这两条:

  • 批量—— 十次 state 更新 合并成一次 DOM 操作, 避免十次重排(见 #288)。
  • 最小化—— 只改真正变了的属性和节点, 不重建整棵子树。

但要说出这层真相(加分点):虚拟 DOM 不一定比手写 DOM 快—— 精心手写的原生操作永远更快, 虚拟 DOM 还额外付出了「建树 + diff」的开销。它真正的价值是「在保持声明式写法的同时, 性能仍然够好」—— 是可维护性和性能的折中, 不是性能银弹。

diff 的三条启发式规则(把 O(n³) 降到 O(n) 的关键):

  1. 只比同层,不跨层移动节点。 跨层的话就是删了重建。
  2. 类型不同直接整棵重建——div 换成 span, 子树全部丢弃重做(state 也丢)。
  3. 同层列表用 key 认身份

key 为什么不能用 index—— 这是 React 面试最实用的一条: 在开头插入或删除一项时, 所有元素的 index 都变了, React 会认为「每一项的内容都变了」, 于是大量误更新; 更糟的是非受控输入框的内容会串到别的行, 因为 DOM 节点被复用了。Q1 那道真题里删除笔记的 bug 就是这个。

In one line: the virtual DOM is a lightweight tree of plain JS objects describing the real DOM. When state changes, React builds a new tree in memory, diffs it against the old one, works out the smallest set of changes, and applies them to the real DOM in one go.

Why it is fast — get these two right:

  • Batching — ten state updates collapse into one DOM write, so you avoid ten reflows (see #288).
  • Minimising — only the attributes and nodes that really changed get touched; whole subtrees are not rebuilt.

But say this part too — it is the bonus point: the virtual DOM is not necessarily faster than hand-written DOM code — carefully tuned native operations always win, and the virtual DOM pays extra for building a tree and diffing it. Its real value is that you keep the declarative style and performance is still good enough — it is a trade-off between maintainability and performance. It is not the right choice everywhere.

The three diff heuristics (what turns O(n³) into O(n)):

  1. Compare the same level only; nodes never move across levels. Crossing a level means delete and rebuild.
  2. A different type rebuilds the whole subtree — swap a div for a span and the subtree is thrown away and redone, state included.
  3. Lists on the same level use key for identity.

Why index must not be the key — the most useful thing you can say in a React interview: insert or delete at the front and every index shifts, so React believes the content of every row changed and does a pile of needless updates; worse, text typed into an uncontrolled input ends up on the wrong row, because the DOM node got reused. The delete-a-note bug in the real Q1 question is exactly this.

JSXkey 的选择Choosing the key示意Illustrative
1// 虚拟 DOM 就是普通对象
2{ type: "button", props: { className: "btn", children: "点我" } }
3
4// ✗ index 当 key:在开头插一项,所有 key 都变了
5{todos.map((t, i) => <Row key={i} todo={t} />)}
6
7// ✓ 稳定的业务 id
8{todos.map((t) => <Row key={t.id} todo={t} />)}
1// The virtual DOM is just a plain object
2{ type: "button", props: { className: "btn", children: "Click me" } }
3
4// ✗ index as key: insert one at the front and every key changes
5{todos.map((t, i) => <Row key={i} todo={t} />)}
6
7// ✓ a stable id from the data
8{todos.map((t) => <Row key={t.id} todo={t} />)}
只有「列表永不重排、不增删中间项」时 index 才安全。既然多数列表都会变,直接养成用 id 的习惯。An index is only safe when the list is never reordered and no item is inserted or removed in the middle. Most lists do change, so make using an id your default habit.
React 与生态React & ecosystem#353

什么是 reconciliation

What is reconciliation

看答案Show answer

一句话:reconciliation(协调)是「比较新旧虚拟 DOM 树, 决定要对真实 DOM 做哪些操作」的整个过程。 diff 算法是它的一部分。

diff 和 reconciliation 什么关系?这是本题的考点:diff 是「怎么比」的算法, reconciliation 是「比 + 决定 + 提交」的完整流程。 说它们是一回事不算错,但分得清更好。

React 16 之后的 Fiber 架构把这个过程拆成两个阶段 —— 这是必答的:

  • render 阶段(可中断)—— 构建 Fiber 树、做 diff、 标记要改什么。这个阶段可以被打断和恢复, 所以高优先级的更新(比如用户输入)能插队。
  • commit 阶段(不可中断)—— 把标记好的改动一次性打到真实 DOM 上, 然后跑 useEffect这一段必须同步完成, 否则用户会看到半渲染的界面。

为什么要能中断?因为老架构(Stack Reconciler)是递归的、一旦开始就停不下来, 大列表更新时会阻塞主线程十几毫秒以上, 输入卡顿。Fiber 用链表 + 循环替代递归, 每处理一小块就检查「有没有更急的事」。这就是「并发特性」的基础(见 #344)。

会追问:「StrictMode 为什么渲染两次?」—— 因为 render 阶段可能被中断和重跑, 所以渲染函数必须是纯的; 两次渲染就是帮你把不纯的地方暴露出来(见 #332)。

In one line: reconciliation is the whole process of comparing the new and old virtual DOM trees and deciding which operations to run on the real DOM. The diff algorithm is one part of it.

How do diff and reconciliation relate? That is the point of the question: diff is the algorithm for how to compare; reconciliation is the full compare, decide and commit flow. Calling them the same thing is not wrong, but telling them apart is better.

The Fiber architecture, from React 16 on, splits the process into two phases — answer this every time:

  • Render phase (interruptible) — build the Fiber tree, diff, mark what has to change. This phase can be paused and resumed, which is how a high-priority update such as typing jumps the queue.
  • Commit phase (not interruptible) — apply the marked changes to the real DOM in one pass, then run useEffect. This part must finish synchronously, otherwise users would see a half-rendered screen.

Why does it need to be interruptible? Because the old Stack Reconciler was recursive and could not stop once it started, so a large list update blocked the main thread for tens of milliseconds and typing stuttered. Fiber replaces recursion with a linked list plus a loop, and after each small chunk it checks whether something more urgent came in. This is the foundation of the concurrent features (see #344).

Follow-up: “Why does StrictMode render twice?” — because the render phase can be interrupted and re-run, so the render function has to be pure; the double render is there to expose the impure parts (see #332).

React 与生态React & ecosystem#337

React 项目里 babel 和 webpack 干什么

What do we use babel and web pack for in React applications

看答案Show answer

一句话分工:Babel 负责「翻译」(JSX 和新语法 → 浏览器能懂的 JS);Webpack 负责「打包」(把一堆模块和资源合并成能上线的几个文件)。

  • Babel——@babel/preset-react 转 JSX,@babel/preset-env按目标浏览器把 ES2020+ 降级。它只做语法转换, 新 API(PromiseArray.flat)要靠 polyfill 补。这个区分是加分点。
  • Webpack—— 解析 import 建依赖图、 让 CSS 和图片也能被 import、 tree shaking、代码分割、 开发时提供 dev server 和热更新。

顺序:Webpack 遇到 .jsx时调用 babel-loaderBabel 是 Webpack 流水线上的一个环节

会追问:「现在还用它们吗?」—— 这题答得出现状才显得在跟进: 新项目多用 Vite(开发用原生 ESM + esbuild, 生产用 Rollup),Babel 常被 esbuild / SWC 取代(快一个量级)。Webpack 仍在大量存量项目和 需要复杂定制的场景里。
我们这门课的 React 源项目用的就是 Vite —— 所以node_modules 里根本没有 webpack。

The split in one line: Babel translates (JSX and new syntax → JS the browser understands); Webpack bundles (a pile of modules and assets become the few files you ship).

  • Babel@babel/preset-react handles JSX, @babel/preset-env down-levels ES2020+ for your target browsers. It only transforms syntax; new APIs (Promise, Array.flat) still need a polyfill. Drawing that line scores points.
  • Webpack — reads your imports to build a dependency graph, lets you import CSS and images too, does tree shaking and code splitting, and gives you a dev server with hot reload while you work.

The order: when Webpack hits a .jsx file it calls babel-loader, so Babel is one stage of the Webpack pipeline.

Follow-up: “Are they still used?” — knowing the current state is what shows you keep up: new projects mostly reach for Vite (native ESM plus esbuild in development, Rollup for production), and Babel is often replaced by esbuild or SWC — an order of magnitude faster. Webpack is still everywhere in existing codebases and wherever heavy customisation is needed.
The React source project in this course uses Vite — which is why there is no webpack in its node_modules at all.

React 与生态React & ecosystem#322

函数组件 vs 类组件

Functional components vs Class components

看答案Show answer

一句话:现在一律写函数组件。 类组件只在维护老代码和写错误边界时才用 (错误边界目前还只能用 class)。

类组件函数组件
状态this.state / setStateuseState
副作用生命周期方法useEffect
this要处理绑定没有 this,不存在这问题
逻辑复用HOC / render props(嵌套很深)自定义 hook(平铺)
代码量

为什么官方推函数组件—— 答这三条比列表格更有说服力:

  • 逻辑能按关注点组织, 而不是按生命周期切碎。 类组件里「订阅」和「取消订阅」被迫分在componentDidMountcomponentWillUnmount 两个方法里;useEffect 让它们写在一起
  • 复用逻辑不用套娃。HOC 叠三层就变成「wrapper 地狱」, 自定义 hook 是平的。
  • this 的问题彻底消失。

会追问:「函数组件里怎么拿 shouldComponentUpdate?」——React.memo, 但它默认是浅比较,需要自定义就传第二个参数。

In one line: write function components, always. Class components are for maintaining old code and for error boundaries, which still have to be classes.

Class componentFunction component
Statethis.state / setStateuseState
Side effectsLifecycle methodsuseEffect
thisYou deal with bindingNo this, so no such problem
Reusing logicHOC / render props (deep nesting)Custom hooks (flat)
Amount of codeMoreLess

Why the official line favours function components — these three points land better than the table:

  • Logic groups by concern instead of being sliced up by lifecycle. In a class, subscribing and unsubscribing are forced apart into componentDidMount and componentWillUnmount; useEffect lets them sit together.
  • Reusing logic needs no nesting. Three stacked HOCs turn into wrapper hell; custom hooks stay flat.
  • The this problem disappears completely.

Follow-up: “How do you get shouldComponentUpdate in a function component?” — React.memo, though it compares shallowly by default; pass a second argument when you need your own comparison.

React 与生态React & ecosystem#323

React 的生命周期有哪些

Explain the React component lifecycle and its methods

看答案Show answer

一句话:三个阶段 ——挂载、更新、卸载

  • 挂载constructorgetDerivedStateFromPropsrendercomponentDidMount(DOM 已经有了,发请求、订阅、操作 DOM 都在这
  • 更新getDerivedStateFromPropsshouldComponentUpdate(返回 false 就跳过渲染)→rendergetSnapshotBeforeUpdatecomponentDidUpdate这里改 state 必须加条件, 否则死循环)
  • 卸载componentWillUnmount(清定时器、解绑监听、取消请求)
  • 出错getDerivedStateFromError +componentDidCatch(错误边界,见 #333)

三个被废弃的要知道componentWillMountcomponentWillReceivePropscomponentWillUpdate原因是 Fiber 的 render 阶段可能被中断和重跑, 这几个方法可能被调用多次, 放在里面的副作用会重复执行。能说出这个原因很加分。

会追问:「请求为什么不放componentWillMount?」—— 除了上面的原因, 它在 SSR 时也会执行, 而且并不会更早拿到数据 (请求是异步的,反正要等)。

In one line: three phases — mounting, updating, unmounting.

  • Mounting: constructor getDerivedStateFromPropsrender componentDidMount (the DOM exists now, so fetching, subscribing and DOM work all belong here)
  • Updating: getDerivedStateFromProps shouldComponentUpdate (return false to skip the render) → render getSnapshotBeforeUpdate componentDidUpdate (setting state here needs a condition, or you get an infinite loop)
  • Unmounting: componentWillUnmount (clear timers, detach listeners, cancel requests)
  • On error: getDerivedStateFromError + componentDidCatch (error boundaries, see #333)

Know the three that were deprecated: componentWillMount, componentWillReceiveProps, componentWillUpdate. The reason is that Fiber can interrupt and re-run the render phase, so these could fire more than once and any side effect inside them would run twice. Giving that reason earns real credit.

Follow-up: “Why not fetch in componentWillMount?” — besides the reason above, it also runs during SSR, and it does not get the data any sooner: the request is async, so you wait either way.

React 与生态React & ecosystem#325

useEffect 和生命周期怎么对应

UseEffect vs Lifecycle Methods

看答案Show answer

一句话(这句要说准):useEffect不是生命周期的替代品, 它是「同步副作用」的另一种思路—— 你声明「这个副作用依赖哪些值」, 值变了它就重新跑。

类组件useEffect 写法
componentDidMountuseEffect(fn, [])
componentDidUpdateuseEffect(fn, [dep])
componentWillUnmounteffect 里 return () => {}
三个都要useEffect(fn)(不写依赖数组)
getSnapshotBeforeUpdateuseLayoutEffect(DOM 更新后、浏览器绘制前同步执行)

但这张表有个陷阱——useEffect(fn, [])不完全等于 componentDidMount: 前者在浏览器绘制之后异步执行,后者是同步的。所以用 useEffect测量 DOM 再改样式会闪一下, 这种情况要用useLayoutEffect

更重要的是别用生命周期的思维写 effect。正确的问法不是「我要在挂载时干什么」, 而是「这个副作用依赖哪些值」。 依赖列全,React 自然会在该跑的时候跑。

会追问:「清理函数什么时候执行?」——依赖变化前卸载时我们那道计时器变式题就是这个考点: 漏了 clearInterval, start/pause 四次会得到 10 秒而不是 4 秒(实测)。

In one line — say this precisely: useEffect is not a replacement for lifecycle methods; it is a different way of thinking about synchronising side effects — you declare which values a side effect depends on, and it re-runs when they change.

Class componentuseEffect form
componentDidMountuseEffect(fn, [])
componentDidUpdateuseEffect(fn, [dep])
componentWillUnmountreturn () => {} inside the effect
All three at onceuseEffect(fn) (no dependency array)
getSnapshotBeforeUpdateuseLayoutEffect (runs synchronously after the DOM updates, before the browser paints)

But the table has a trap useEffect(fn, []) is not quite componentDidMount: the first runs asynchronously after the browser paints, the second is synchronous. So measuring the DOM in a useEffect and then changing styles will flash; that case wants useLayoutEffect.

More important: stop writing effects with a lifecycle mindset. The right question is not “what do I do on mount” but “which values does this side effect depend on”. List the dependencies properly and React runs it when it should.

Follow-up: “When does the cleanup function run?” — before the dependencies change and on unmount. Our timer variant question tests exactly this: drop the clearInterval and four start/pause rounds give you 10 seconds instead of 4 (measured).

React 与生态React & ecosystem#327

props vs state

props vs state

看答案Show answer

一句话:props 是父组件传进来的、只读state 是组件自己的、可变

propsstate
谁拥有父组件组件自己
能否修改不能(只读)能,通过 setState
变了会重渲染吗

为什么 props 必须只读?因为组件的渲染函数应该是纯的(见 #293):同样的 props 渲染出同样的 UI。 改了 props 就等于改了「输入」, 父组件下次渲染又会把它覆盖回去 —— 数据源变成两个,谁也说不清现在该信谁。

怎么判断该用哪个(实用判据):

  • 能从 props 或别的 state 算出来都别放,直接算(派生数据)
  • 只有这个组件关心、且会变 → state
  • 多个组件都要用 → 提到共同父级(#345)
  • 整棵树都要用且不常变 → Context

会追问:「能把 props 存进 state 吗?」——能但通常是 buguseState(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.

propsstate
Who owns itThe parentThe component itself
Can you change itNo (read-only)Yes, through setState
Does a change re-renderYesYes

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.

React 与生态React & ecosystem#328

组件之间怎么通信

Communication between components

看答案Show answer

一句话:五种,按「距离」从近到远选。

  • 父 → 子:props。
  • 子 → 父: 父把回调函数当 props 传下去, 子调用它。「事件往上报」就是这个。
  • 兄弟之间状态提升到共同父级, 再分别往下传(#345)。
  • 跨很多层Context—— 适合主题、当前用户、语言这种 「整棵树都要读、又不常变」的值。
  • 全局、复杂、多处修改: 状态库(Redux / Zustand / Jotai) 或服务端状态库(TanStack Query)。

还有两个偏门但会问的:ref +useImperativeHandle(父组件主动调子组件的方法, 比如 focus()play()); 以及 props.children(组合优于配置,也是解决 props drilling 的一招)。

会追问:「什么时候该上状态库?」—— 判据:同一份状态被很多不相关的组件读写、 或者需要时间旅行调试 / 中间件只是「层数深」不该上 Redux, Context 或组合就够—— 这个回答比「大项目就用 Redux」好得多。

In one line: five ways, and you pick by distance — nearest first.

  • Parent → child: props.
  • Child → parent: the parent passes a callback down as a prop and the child calls it. That is all “events go up” means.
  • Between siblings: lift the state to their common parent and pass it back down to each one (#345).
  • Across many levels: Context — good for theme, current user, language: values the whole tree reads and that rarely change.
  • Global, complex, written from many places: a state library (Redux / Zustand / Jotai) or a server-state library (TanStack Query).

Two less common ones they still ask about: ref plus useImperativeHandle (the parent calls a method on the child, say focus() or play()); and props.children (composition over configuration, which is also one answer to props drilling).

Follow-up: “When should you reach for a state library?” — the test: one piece of state is read and written by many unrelated components, or you need time-travel debugging or middleware. Depth alone is no reason for Redux — Context or composition is enough — that answer beats “big project, use Redux” by a mile.

JSX两种最常用的方式示意Illustrative
1// 子 -> 父:传回调下去
2function Parent() {
3 const [text, setText] = useState("");
4 return <Child onChange={setText} />; // 父给回调
5}
6function Child({ onChange }) {
7 return <input onChange={(e) => onChange(e.target.value)} />;
8}
9
10// 用 children 组合,避免中间层被迫透传
11<Layout sidebar={<Nav />}>
12 <Article /> {/* Layout 不需要知道 Article 要什么 props */}
13</Layout>
1// Child to parent: pass a callback down
2function Parent() {
3 const [text, setText] = useState("");
4 return <Child onChange={setText} />; // the parent supplies the callback
5}
6function Child({ onChange }) {
7 return <input onChange={(e) => onChange(e.target.value)} />;
8}
9
10// Compose with children, so the middle layer is not forced to pass things through
11<Layout sidebar={<Nav />}>
12 <Article /> {/* Layout does not need to know what props Article wants */}
13</Layout>

这些题从哪来Where these come from

99 道来自面试题库 #269–#387;TypeScript 深度那 6 道是 DrillLab 自出的(senior 补强,卡片上有标注)。答案都是 DrillLab 写的,所以讲解里的代码块一律标「示意」。每道题都能点回它出处的那一节课。99 questions come from the interview bank (#269–#387); the 6 TypeScript deep-dive ones are DrillLab-made (marked on the card). All answers are written by DrillLab, so every code block here is labelled “demo”. Each card links back to the lesson it came from.