通常,你需要从其他状态派生状态。为此,我们有 $derived
符文:
¥Often, you will need to derive state from other state. For this, we have the $derived
rune:
App
let numbers = $state([1, 2, 3, 4]);
let total = $derived(numbers.reduce((t, n) => t + n, 0));
我们现在可以在标记中使用它:
¥We can now use this in our markup:
App
<p>{numbers.join(' + ')} = {total}</p>
每当其依赖(在本例中仅为 numbers
)更新时,$derived
声明中的表达式都会被重新评估。与正常状态不同,派生状态是只读的。
¥The expression inside the $derived
declaration will be re-evaluated whenever its dependencies (in this case, just numbers
) are updated. Unlike normal state, derived state is read-only.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let numbers = $state([1, 2, 3, 4]);
function addNumber() {
numbers.push(numbers.length + 1);
}
</script>
<p>{numbers.join(' + ')} = ...</p>
<button onclick={addNumber}>
Add a number
</button>