正如我们在上一个练习中看到的,状态会对重新分配做出反应。但它也会对突变做出反应 - 我们称之为深度反应。
¥As we saw in the previous exercise, state reacts to reassignments. But it also reacts to mutations — we call this deep reactivity.
将 numbers
设为反应数组:
¥Make numbers
a reactive array:
App
let numbers = $state([1, 2, 3, 4]);
现在,当我们更改数组时……
¥Now, when we change the array...
App
function addNumber() {
numbers[numbers.length] = numbers.length + 1;
}
...组件更新。或者更好的是,我们可以将 push
改为数组:
¥...the component updates. Or better still, we can push
to the array instead:
App
function addNumber() {
numbers.push(numbers.length + 1);
}
使用 proxies 实现深度反应性,对代理的修改不会影响原始对象。
¥[!NOTE] Deep reactivity is implemented using proxies, and mutations to the proxy do not affect the original object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let numbers = [1, 2, 3, 4];
function addNumber() {
// TODO implement
}
</script>
<p>{numbers.join(' + ')} = ...</p>
<button onclick={addNumber}>
Add a number
</button>