mirror of
https://github.com/sveltejs/svelte.git
synced 2024-11-30 00:46:29 +01:00
[docs] clarify array methods that won't trigger reactivity (#7073)
Co-authored-by: Tan Li Hau <tanhauhau@users.noreply.github.com> Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> Co-authored-by: Gabor Szabo <gabor@szabgab.com> Co-authored-by: gtmnayan <50981692+gtm-nayan@users.noreply.github.com>
This commit is contained in:
parent
0ed6ebef9d
commit
8b828a4301
@ -2,9 +2,11 @@
|
||||
title: Updating arrays and objects
|
||||
---
|
||||
|
||||
Because Svelte's reactivity is triggered by assignments, using array methods like `push` and `splice` won't automatically cause updates. For example, clicking the button doesn't do anything.
|
||||
Svelte's reactivity is triggered by assignments. Methods that mutate arrays or objects will not trigger updates by themselves.
|
||||
|
||||
One way to fix that is to add an assignment that would otherwise be redundant:
|
||||
In this example, clicking the "Add a number" button calls the `addNumber` function, which appends a number to the array but doesn't trigger the recalculation of `sum`.
|
||||
|
||||
One way to fix that is to assign `numbers` to itself to tell the compiler it has changed:
|
||||
|
||||
```js
|
||||
function addNumber() {
|
||||
@ -13,7 +15,7 @@ function addNumber() {
|
||||
}
|
||||
```
|
||||
|
||||
But there's a more idiomatic solution:
|
||||
You could also write this more concisely using the ES6 spread syntax:
|
||||
|
||||
```js
|
||||
function addNumber() {
|
||||
@ -21,7 +23,7 @@ function addNumber() {
|
||||
}
|
||||
```
|
||||
|
||||
You can use similar patterns to replace `pop`, `shift`, `unshift` and `splice`.
|
||||
The same rule applies to array methods such as `pop`, `shift`, and `splice` and to objects methods such as `Map.set`, `Set.add`, etc.
|
||||
|
||||
Assignments to *properties* of arrays and objects — e.g. `obj.foo += 1` or `array[i] = x` — work the same way as assignments to the values themselves.
|
||||
|
||||
@ -31,11 +33,22 @@ function addNumber() {
|
||||
}
|
||||
```
|
||||
|
||||
A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...
|
||||
However, indirect assignments to references such as this...
|
||||
|
||||
```js
|
||||
const foo = obj.foo;
|
||||
foo.bar = 'baz';
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```js
|
||||
function quox(thing) {
|
||||
thing.foo.bar = 'baz';
|
||||
}
|
||||
quox(obj);
|
||||
```
|
||||
|
||||
...won't trigger reactivity on `obj.foo.bar`, unless you follow it up with `obj = obj`.
|
||||
|
||||
A simple rule of thumb: the updated variable must directly appear on the left hand side of the assignment.
|
Loading…
Reference in New Issue
Block a user