如何安装svelte_在Svelte中处理状态更新

如何安装svelte

One great thing about Svelte is that you don’t need to do anything special to update the state of a component.

Svelte的一大优点是您无需执行任何特殊操作即可更新组件的状态。

All you need is an assignment.

您所需要做的只是一项任务。

Say you have a count variable. You can increment that using, simply, count = count + 1, or count++:

假设您有一个count变量。 您可以简单地使用count = count + 1count++来增加它:

<script>
let count = 0

const incrementCount = () => {
	count++
}
</script>

{count} <button on:click={incrementCount}>+1</button>

This is nothing groundbreaking if you are unfamiliar with how modern Web frameworks handle state, but in React you’d have to either call this.setState(), or use the useState() hook.

如果您不熟悉现代Web框架如何处理状态,那么这并不是开创性的,但是在React中,您必须调用this.setState()或使用useState()挂钩。

Vue takes a more structured approach using classes and the data property.

Vue使用类和data属性采用了更结构化的方法。

Having used both, I find Svelte to be a much more JavaScript-like syntax.

两者都使用过后,我发现Svelte是一种更像JavaScript的语法。

We need to be aware of one thing, which is learned pretty quickly: we must also do an assignment when changing the value.

我们需要注意一件事,这很快就会学到:更改值时还必须进行赋值。

For simple values like strings and numbers, that’s mostly a given, because all methods on String return new strings, and same for numbers - they are immutable.

对于诸如字符串和数字之类的简单值,这通常是给定的,因为String上的所有方法都返回新的字符串,数字也一样,它们都是不可变的。

But for arrays? We can’t use methods that alter the array. Like push(), pop(), shift(), splice()… because there’s no assignment. They change the inner data structure, but Svelte can’t detect that.

但是对于数组? 我们不能使用改变数组的方法。 像push()pop()shift()splice() ,因为没有分配。 他们更改了内部数据结构,但Svelte无法检测到。

Well, you can still use them, but after you’ve done your operation, you reassign the variable to itself, like this:

好的,您仍然可以使用它们,但是在完成操作之后,您可以将变量重新分配给它自己,如下所示:

let list = [1, 2, 3]
list.push(4)
list = list

Which is a bit counter-intuitive, but you’ll quickly remember it.

这有点违反直觉,但是您会很快记住它。

Or you can use use the spread operator to perform operations:

或者,您可以使用传播操作符执行操作:

let list = [1, 2, 3]
list = [...list, 4]

翻译自: https://flaviocopes.com/svelte-reactive-assignments/

如何安装svelte

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值