React Cab Booking(Context 版)React Cab Booking (Context version)
一个用 Context 管全局状态的打车小应用。四个页面、一个 Context、四个测试。练的是「Context 在一个真实多页应用里怎么用」—— Provider 放在哪一层、一个 action 同时改两个 state、消费者散在三个组件里。A small cab booking app that keeps its global state in a Context. Four pages, one Context, four tests. The practice here is how to use Context in a real app with several pages: which level the Provider goes on, one action updating two pieces of state at once, and readers of the Context spread across three components.
Context 三件套与 Provider 的层级、一次更新两个 state、页面状态机、数组取尾部三条并反转、useEffect 的 setTimeout 清理、data-testid 契约。附带一个真实的脚手架缺陷:完整答案原样跑不起来。The three parts of Context and the level the Provider sits at, updating two pieces of state in one action, the page state machine, taking the last three items of an array and reversing them, clearing a setTimeout inside useEffect, and the data-testid contract. Plus one real defect in the provided project: the complete answer does not run as given.
cab-booking-context参考项目。6 个组件 + 1 个 Context + 4 个测试Reference project. Six components, one Context, four tests
cab-booking-context建议先过一遍Work through 地基 · 项目与语言。如果你已经会 npm、会读 package.json,可以直接开始这一门。 first. If you already know npm and can read a package.json, start here directly.
| 真实项目里的任务Task in the real project | DrillLab 讲到哪Where DrillLab covers it | 有测试Tested |
|---|---|---|
| 首页 + 空历史提示 | 第 1 部分 · 先读四个测试 | 有Yes |
| Context 三件套 + Provider 层级 | 第 1 部分 · Context 放在哪一层 | 有Yes |
| 一个 action 改两个 state | 第 1 部分 · 一次更新两个 state | 有Yes |
| 四个页面的切换 | 第 2 部分 · 页面状态机 | 有Yes |
| 按类型分组 + 六张卡的字段 | 第 2 部分 · 分组渲染与 testid 契约 | 有Yes |
| Loading 一秒后自动跳转 | 第 2 部分 · setTimeout 与清理函数 | 有Yes |
| 历史只留最新三条、最新在最上 | 第 2 部分 · slice(-3).reverse() | 有Yes |
| 脚手架缺陷:.js 里写 JSX | 第 3 部分 · Debug Lab | 有Yes |
| 两处能更好的写法(面试会问) | 第 3 部分 · 面试官会追问的两点 | 无No |
| 空文件夹里从零重写 | 第 3 部分 · 从零重写 | 有Yes |
先把四个测试读清楚,再搭 Context。这一部分的核心是一个位置问题:Provider 到底该包在哪一层 —— 答错这个,App 自己就用不了 Context。Read the four tests carefully first, then build the Context. The main point of this part is a question of position: which level of the tree the Provider should wrap. Get that wrong and App itself cannot read the Context.
没有路由,一个 currentPage state 管四个页面。这一部分把页面写出来,顺便撞上两个老考点:effect 的清理函数、和「取最新三条」的数组操作。No router: a single currentPage state controls four pages. This part builds the pages, and it also covers two points that come up again and again: the cleanup function of an effect, and the array operation that takes the three newest items.
三件事:修掉那个让「完整答案」原样跑不起来的缺陷;把源项目两处「测试能过但面试会被问」的写法说清楚;然后在空文件夹里重写一遍。Three things: fix the defect that stops the complete answer from running as given; explain two places in the source project where the code passes the tests but an interviewer would still ask about it; then write the whole app again in an empty folder.