一个实战示例:"收藏"功能
我们来端到端地做一个小功能:用户可以把列表里的条目标记为收藏,并看到自己收藏了多少个的计数。
切分它
我会这样把它拆成纵向步骤:
- 在每个条目旁边加一个星标按钮(暂时什么都不做,只是显示出来)。
- 点击星标切换它的亮/灭外观(仅状态,不保存)。
- 显示一个反映这些切换的"★ 3 favorites"计数器。
- 保存收藏,让它在页面重新加载后依然存在。
注意每一步都可独立运行、可见。你在其中任何一步之后停下,都仍然拥有一个可运行的应用。
第 1 步:按钮
一条好的提示会点明文件、改动,以及不要碰什么:
In the ItemCard component (src/components/ItemCard.jsx), add a star
button in the top-right corner of each card. It should render an
outline star icon. Don't wire up any click behavior yet — just make
it appear. Keep the rest of the card layout unchanged.
运行应用。看到星标了吗?好。提交:
git add -A && git commit -m "Add star button to item cards"
第 2 步:切换状态
Make the star button toggle between filled and outline when clicked.
Track this with local component state — don't save it anywhere yet.
A filled star means favorited.
现在你在同时处理状态和 UI,这很正常。AI 大概会加上类似这样的东西:
const [isFavorite, setIsFavorite] = useState(false);
<button onClick={() => setIsFavorite(!isFavorite)}>
{isFavorite ? <StarFilled /> : <StarOutline />}
</button>
点几下星标。它们会切换吗?提交。
第 3 步:计数器
Add a "★ N favorites" counter at the top of the item list. It should
count how many items currently have their star filled. Lift the
favorite state up to the list component if you need to so the counter
can see it.
这一步可能要求 AI 重构状态所在之处——这在预料之中,而这恰恰是为什么你要把它作为独立的小步骤来做。运行它,切换几个星标,看着数字变化。提交。
第 4 步:让它持久化
Persist favorites so they survive a page reload. Use localStorage for
now — save the list of favorited item IDs whenever it changes, and
load it on startup.
重新加载页面。还是收藏状态吗?你刚刚交付了一个功能,一次一个可运行的切片。