Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

正如我们在上一个练习中看到的,状态会对重新分配做出反应。但它也会对突变做出反应 - 我们称之为深度反应。

¥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>