Svelte 튜토리얼 번역 | 2. 반응성

moseoridev·2021년 12월 23일
0

(현재 지속적으로 업데이트 중입니다.)
(기술용어는 가능한 원어를 사용하였습니다.)

a. 할당

이벤트에 대한 응답과 같이 DOM을 앱 상태와 동기화하기 위한 강력한 반응성 시스템은 Svelte의 핵심입니다.

이를 시연하기 위해서는 이벤트 handler를 연결해야 합니다. 9번 줄을 이것으로 교체하세요:

<button on:click={incrementCount}>

incrementCount 함수 안에서 count 값을 바꾸기만 하면 됩니다:

function incrementCount() {
	count += 1;
}

Svelte는 DOM이 업데이트되어야 한다고 알려주는 코드로 이 할당을 '계측' 합니다.


b. 선언

Svelte는 컴포넌트의 상태가 변할 때 자동으로 DOM을 업데이트합니다. 가끔 컴포넌트 상태의 일부가 다른 부분에서 계산되어야 하고 (firstnamelastname에서 나온 fullname과 같이), 다른 부분이 변경될 때마다 다시 계산해야 합니다.

이러한 경우를 위해 reactive 선언이 있습니다. 이렇게 쓰죠:

let count = 0;
$: doubled = count * 2;

이 코드가 좀 이상하게 보이더라도 걱정하지 마세요. 이건 Svelte가 '참조값이 변할 때마다 코드를 다시 실행하라'고 해석하는 올바른 (unconventional 하다면) JavaScript 코드입니다. 익숙해진다면 잊을 수 없을 겁니다.

doubled를 markup에서 사용해 봅시다:

<p>{count} doubled is {doubled}</p>

물론 markup에 {count * 2}라고 써버릴 수도 있습니다 — reactive value를 반드시 써야 하는건 아닙니다. Reactive value는 value를 여러 번 참조해야 하거나, 다른 reactive value에 의존하는 value가 있을 때 특히 빛을 발합니다.


c. 상태

Reactive value를 선언하는 것에만 국한되지 않습니다 — 또한 임의의 statements를 반응적으로 실행할 수 있습니다. 예를 들어 count의 값이 변할 때마다 로그를 찍을 수 있습니다:

$: console.log('the count is ' + count);

블록을 사용해서 쉽게 statements를 그룹화할 수 있습니다:

$: {
	console.log('the count is ' + count);
	alert('I SAID THE COUNT IS ' + count);
}

if 블록과 같은 것 앞에도 $:를 놓을 수 있습니다:

$: if (count >= 10) {
	alert('count is dangerously high!');
	count = 9;
}

d. 배열과 객체 업데이트

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.

One way to fix that is to add an assignment that would otherwise be redundant:

function addNumber() {
	numbers.push(numbers.length + 1);
	numbers = numbers;
}

But there's a more idiomatic solution:

function addNumber() {
	numbers = [...numbers, numbers.length + 1];
}

You can use similar patterns to replace pop, shift, unshift and splice.

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.

function addNumber() {
	numbers[numbers.length] = numbers.length + 1;
}

A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...

const foo = obj.foo;
foo.bar = 'baz';

...won't trigger reactivity on obj.foo.bar, unless you follow it up with obj = obj.

profile
코딩하는 학생

0개의 댓글