任务
按顺序折叠动作:已知类型返回新对象,未知类型直接返回原状态,全过程不得修改输入。
契约
- 输入:JSON 对象:{ state: object, actions: [{ type, payload? }] }
- 输出:JSON 对象:最终状态
样例
- 输入
{"state":{"count":0,"label":"idle"},"actions":[{"type":"increment"},{"type":"increment"},{"type":"setLabel","payload":"running"}]}-> 期望{"count":2,"label":"running"}。自增动作累积生效,label 动作替换对应字段。 - 输入
{"state":{"count":1},"actions":[{"type":"unknown"}]}-> 期望{"count":1}。未知动作不会改动状态。
参考实现
function solve({ state, actions }) {
let current = { ...state };
for (const action of actions) {
if (action.type === 'increment') current = { ...current, count: current.count + 1 };
else if (action.type === 'decrement') current = { ...current, count: current.count - 1 };
else if (action.type === 'setLabel') current = { ...current, label: action.payload };
}
return current;
}
为什么有效
reducer 是 React 状态中可测试的核心。原地修改状态会让渲染不可靠;返回新对象才能让每次状态迁移可复现。
每个分支都必须返回新对象;原地写入会让状态迁移无法测试。