@@ -2,11 +2,28 @@ import React from '../core/React';
2
2
3
3
import './index.css' ;
4
4
5
+ function TodoItem ( { todo, handleRemove, handleStatusChange } ) {
6
+ const className = todo . isDone ? 'done' : '' ;
7
+
8
+ return (
9
+ < li >
10
+ < span className = { className } > { todo . name } </ span >
11
+ < button onClick = { ( ) => handleRemove ( todo . id ) } > remove</ button >
12
+ < button onClick = { ( ) => handleStatusChange ( todo . id ) } >
13
+ { todo . isDone ? 'cancel' : 'done' }
14
+ </ button >
15
+ </ li >
16
+ ) ;
17
+ }
18
+
5
19
function ToDos ( ) {
6
- const originList = localStorage . getItem ( 'todos' )
7
- ? JSON . parse ( localStorage . getItem ( 'todos' ) )
8
- : [ ] ;
9
- const [ todoList , setTodoList ] = React . useState ( originList ) ;
20
+ const [ todoList , setTodoList ] = React . useState ( [ ] ) ;
21
+ React . useEffect ( ( ) => {
22
+ const list = localStorage . getItem ( 'todos' ) ;
23
+ if ( list ) {
24
+ setTodoList ( JSON . parse ( list ) ) ;
25
+ }
26
+ } , [ ] ) ;
10
27
11
28
function handleAdd ( ) {
12
29
const inputEl = document . querySelector ( '#input' ) ;
@@ -32,15 +49,16 @@ function ToDos() {
32
49
useDoneStatus ( doneStatus ) ;
33
50
}
34
51
35
- function handleRemove ( index ) {
36
- const newList = [ ...todoList ] ;
37
- newList . splice ( index , 1 ) ;
52
+ function handleRemove ( id ) {
53
+ const newList = todoList . filter ( ( todo ) => todo . id !== id ) ;
38
54
setTodoList ( newList ) ;
39
55
}
40
56
41
- function handleStatusChange ( index ) {
42
- const newList = [ ...todoList ] ;
43
- newList [ index ] . isDone = ! newList [ index ] . isDone ;
57
+ function handleStatusChange ( id ) {
58
+ const newList = todoList . map ( ( todo ) => ( {
59
+ ...todo ,
60
+ isDone : todo . id === id ? ! todo . isDone : todo . isDone
61
+ } ) ) ;
44
62
setTodoList ( newList ) ;
45
63
}
46
64
@@ -94,17 +112,13 @@ function ToDos() {
94
112
if ( doneStatus === 'done' ) return todo . isDone ;
95
113
return ! todo . isDone ;
96
114
} )
97
- . map ( ( todo , index ) => {
98
- const className = todo . isDone ? 'done' : '' ;
99
-
115
+ . map ( ( todo ) => {
100
116
return (
101
- < li >
102
- < span className = { className } > { todo . name } </ span >
103
- < button onClick = { ( ) => handleRemove ( index ) } > remove</ button >
104
- < button onClick = { ( ) => handleStatusChange ( index ) } >
105
- { todo . isDone ? 'cancel' : 'done' }
106
- </ button >
107
- </ li >
117
+ < TodoItem
118
+ todo = { todo }
119
+ handleRemove = { handleRemove }
120
+ handleStatusChange = { handleStatusChange }
121
+ />
108
122
) ;
109
123
} ) }
110
124
</ ul >
0 commit comments