1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import { useReducer } from 'react'; import AddTask from './AddTask.js'; import TaskList from './TaskList.js';
export default function TaskApp() { const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
function handleAddTask(text) { dispatch({ type: 'added', id: nextId++, text: text, }); }
function handleChangeTask(task) { dispatch({ type: 'changed', task: task, }); }
function handleDeleteTask(taskId) { dispatch({ type: 'deleted', id: taskId, }); }
return ( <> <h1>布拉格的行程安排</h1> <AddTask onAddTask={handleAddTask} /> <TaskList tasks={tasks} onChangeTask={handleChangeTask} onDeleteTask={handleDeleteTask} /> </> ); }
function tasksReducer(tasks, action) { switch (action.type) { case 'added': { return [ ...tasks, { id: action.id, text: action.text, done: false, }, ]; } case 'changed': { return tasks.map((t) => { if (t.id === action.task.id) { return action.task; } else { return t; } }); } case 'deleted': { return tasks.filter((t) => t.id !== action.id); } default: { throw Error('未知 action: ' + action.type); } } }
let nextId = 3; const initialTasks = [ {id: 0, text: '参观卡夫卡博物馆', done: true}, {id: 1, text: '看木偶戏', done: false}, {id: 2, text: '打卡列侬墙', done: false} ];
|