$inspect
$inspect仅在开发期间有效。在生产版本中,它将变为空操作。
$inspect 符文大致相当于 console.log,不同之处在于它会在其参数发生变化时重新运行。$inspect 深度跟踪反应状态,这意味着使用细粒度反应更新对象或数组内部的某些内容将导致其重新触发(demo):
¥The $inspect rune is roughly equivalent to console.log, with the exception that it will re-run whenever its argument changes. $inspect tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire (demo):
<script>
let count = $state(0);
let message = $state('hello');
$inspect(count, message); // will console.log when `count` or `message` change
</script>
<button onclick={() => count++}>Increment</button>
<input bind:value={message} />更新时,会打印堆栈跟踪,方便查找状态变化的来源(除非由于技术限制,你在 Playground 中)。
¥On updates, a stack trace will be printed, making it easy to find the origin of a state change (unless you’re in the playground, due to technical limitations).
$inspect(...).with
$inspect 返回一个属性 with,你可以使用回调来调用它,然后将调用回调而不是 console.log。回调的第一个参数是 "init" 或 "update";后续参数是传递给 $inspect (demo) 的值:
¥$inspect returns a property with, which you can invoke with a callback, which will then be invoked instead of console.log. The first argument to the callback is either "init" or "update"; subsequent arguments are the values passed to $inspect (demo):
<script>
let count = $state(0);
$inspect(count).with((type, count) => {
if (type === 'update') {
debugger; // or `console.trace`, or whatever you want
}
});
</script>
<button onclick={() => count++}>Increment</button>$inspect.trace(...)
此符文在 5.14 中添加,导致在开发中跟踪周围的函数。任何时候函数作为 effect 或 derived 的一部分重新运行时,都会将有关哪些反应状态导致效果触发的信息打印到控制台。
¥This rune, added in 5.14, causes the surrounding function to be traced in development. Any time the function re-runs as part of an effect or a derived, information will be printed to the console about which pieces of reactive state caused the effect to fire.
<script>
import { doSomeWork } from './elsewhere';
$effect(() => {
// $inspect.trace must be the first statement of a function body
$inspect.trace();
doSomeWork();
});
</script>$inspect.trace 采用可选的第一个参数,该参数将用作标签。
¥$inspect.trace takes an optional first argument which will be used as the label.