回答編集履歴
2
spliceの使い方間違ってました
answer
CHANGED
@@ -33,16 +33,16 @@
|
|
33
33
|
});
|
34
34
|
}
|
35
35
|
delete(idx) {
|
36
|
-
const todoList = this.state.todoList;
|
36
|
+
const todoList = [...this.state.todoList];
|
37
|
-
this.setState({
|
38
|
-
|
37
|
+
todoList.splice(idx, 1);
|
39
|
-
});
|
38
|
+
this.setState({ todoList });
|
40
39
|
}
|
41
40
|
complete(idx) {
|
42
|
-
const todoList = this.state.todoList;
|
41
|
+
const todoList = [...this.state.todoList];
|
42
|
+
const [completeTodo] = todoList.splice(idx, 1);
|
43
43
|
this.setState({
|
44
|
-
todoList
|
44
|
+
todoList,
|
45
|
-
completeList: [...this.state.completeList,
|
45
|
+
completeList: [...this.state.completeList, completeTodo],
|
46
46
|
});
|
47
47
|
}
|
48
48
|
```
|
1
スプレッド構文の結果間違ってたのと言い回しの修正
answer
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
この原因と直接関係あるかはわかりませんが、reactではprops/stateは基本的にイミュータブルである必要があり、これを守らないとundo機能を実装しようとした時に困ったり
|
1
|
+
この原因と直接関係あるかはわかりませんが、reactではprops/stateは基本的にイミュータブルである必要があり、これを守らないとバグが発生する確率が上がったりundo機能を実装しようとした時に困ったりします。
|
2
2
|
|
3
3
|
イミュータブルとは不変という意味で、例えば配列であれば以下のように破壊的な変更をすると`arr1`だけでなく`arr2`も変わってしまいます。
|
4
4
|
こうならないために値を追加/削除/上書きしたい時には`arr3`のように新しい配列を作る必要があります。
|
@@ -14,10 +14,10 @@
|
|
14
14
|
const arr1 = [1, 2, 3];
|
15
15
|
const arr2 = arr1;
|
16
16
|
const arr3 = [...arr1];
|
17
|
-
arr1.push(
|
17
|
+
arr1.push(4);
|
18
|
+
console.log(arr1); // [1, 2, 3, 4]
|
19
|
+
console.log(arr2); // [1, 2, 3, 4]
|
18
|
-
console.log(
|
20
|
+
console.log(arr3); // [1, 2, 3]
|
19
|
-
console.log(arr2); // [1, 2]
|
20
|
-
console.log(arr3); // [1]
|
21
21
|
```
|
22
22
|
|
23
23
|
本題のcompleteですが、`completeList`を`todoList`で上書きしてしまっているためでしょう。
|