# Todo-List By React (二) sort important
[Todo-List By React (一) 增加 todo](https://hackmd.io/@AlbusFu/rkjlmMDWj)
**[Todo-List By React (二) sort important](https://hackmd.io/9l5glQL5Sey2i16Qw9RcBA)**
[Todo-List By React (三) router and decoration](https://hackmd.io/Cf0LAxJUQRiybV-eh6ucWw)
參考[前端修練精神時光屋 2018 - 第一週 - todolist](https://hexschool.github.io/THE_F2E_Design/todolist/)的版型,可以點進去看看設計稿
今天在要加入 completed, important 兩個勾選欄,資料不那麼單純了,要把 useState 換成 useReducer
也會有對資料有越來越多的操作,所以做一個 hook 來放置資料,跟做一些操作。
useTodoList架構大概長這樣
```
const [todoList, dispatch] = useReducer(reducer, initTodoList)
// reducer 的 action.type 目前有 'ADD', 'UPDATE'
// 把渲染資料跟資料庫本身分開
// 一來不會直接接觸到,比較安全
// 二來之後對資料做操作(排序、篩選),也不會動到原檔
const renderTodoList = todoList
return {renderTodoList, dispatch}
```
把資料串一串......
確認一下功能是不是跟之前一樣,能新增新的事項,能修改事項。
## 接下來,先處理簡單的部分
在 Form 元件加上 completed, important 兩個勾選欄
```
// 空的資料
cosnt initTodo = {
completed: false,
title: '',
checked: '',
}
const [todo, setTodo] = useState(initTodo)
// 兩個 checkbox 長得差不多,名字不一樣而已
<input type='checkbox'
onChange={e => {setTodo({
...todo,
completed: e.target.checked
})}}
/>
```
再來處理 Todo 元件
```
const todo = props.todo
// 兩個 checkbox 長得差不多,名字不一樣而已
<input type='checkbox'
checked={todo.completed}
onChange={e => {
todo.completed = e.target.value
dispatch({
action: 'UPDATAE',
payload: todo,
})
}}
```
## 時間還夠,把 important 排序吧
回到 useTodoList,這時候 renderTodoList 派上用場了。
```
function importantSorter(todoList) {
const important = []
const unimportant = []
todoList.forEach(todo => {
if(todo.important){
important.push(todo)
}else{
unimportant.push(todo)
}
})
return [...important, ...unimportant]
}
const renderTodoList = importantSorter(todoList)
```
今天差不多就這樣,中途還大大卡關,只好上網求助,結果是 checkbox 值搞錯位置,它是放在 checked 而不是 value =3=
明天來弄 Router。
[GitHub version-1 程式碼](https://github.com/GeminiFu/todo-list-2/tree/master/version/version1/src)
[GitHub最新進度](https://geminifu.github.io/todo-list-2/dist/index.html)
<iframe src="https://geminifu.github.io/todo-list-2/dist/index.html" width="650px" height="600px"></iframe>
參考範本:
[前端修練精神時光屋 2018 - 第一週 - todolist](https://challenge.thef2e.com/news/1)