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

能够跟踪状态随时间变化的值通常很有用。

¥It’s often useful to be able to track the value of a piece of state as it changes over time.

addNumber 函数中,我们添加了 console.log 语句。但如果你单击按钮并打开控制台抽屉(使用 URL 栏右侧的按钮),你会看到一条警告,以及一条消息,提示无法克隆该消息。

¥Inside the addNumber function, we’ve added a console.log statement. But if you click the button and open the console drawer (using the button to the right of the URL bar), you’ll see a warning, and a message saying the message could not be cloned.

这是因为 numbers 是反应式 proxy。我们可以做几件事。首先,我们可以使用 $state.snapshot(...) 创建状态的非反应性快照:

¥That’s because numbers is a reactive proxy. There are a couple of things we can do. Firstly, we can create a non-reactive snapshot of the state with $state.snapshot(...):

App
function addNumber() {
	numbers.push(numbers.length + 1);
	console.log($state.snapshot(numbers));
}

或者,我们可以使用 $inspect 符文在状态发生变化时自动记录状态快照。此代码将自动从你的生产版本中删除:

¥Alternatively, we can use the $inspect rune to automatically log a snapshot of the state whenever it changes. This code will automatically be stripped out of your production build:

App
function addNumber() {
	numbers.push(numbers.length + 1);
	console.log($state.snapshot(numbers));
}

$inspect(numbers);

你可以使用 $inspect(...).with(fn) 自定义信息的显示方式 - 例如,你可以使用 console.trace 查看状态更改的来源:

¥You can customise how the information is displayed by using $inspect(...).with(fn) — for example, you can use console.trace to see where the state change originated from:

App
$inspect(numbers).with(console.trace);
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
	let numbers = $state([1, 2, 3, 4]);
	let total = $derived(numbers.reduce((t, n) => t + n, 0));
 
	function addNumber() {
		numbers.push(numbers.length + 1);
		console.log(numbers);
	}
</script>
 
<p>{numbers.join(' + ')} = {total}</p>
 
<button onclick={addNumber}>
	Add a number
</button>