gpt4 book ai didi

javascript - setState() 对于更新 Alt.js 存储中的状态是可选的吗?

转载 作者:行者123 更新时间:2023-11-28 18:14:17 24 4
gpt4 key购买 nike

是的,我知道 setState() 会更新 Store 的状态并向所有订阅者发出更改事件,但我发现并不是每个人都使用它并忽略它当他们更新状态时。

例如下面的alt-todo repo ,他们不使用 setState():

class TodoStore {
constructor() {
this.bindActions(TodoActions);

this.todos = {};
}

onCreate(text) {
text = text.trim()
if (text === '') {
return false
}
// hand waving of course.
const id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36)
this.todos[id] = {
id: id,
complete: false,
text: text
}
}
}

但是在 official alt.js repo他们使用它:

class LocationStore {
constructor() {
this.bindAction(locationActions.updateLocation, this.onUpdateLocation);

this.state = {
city: 'Denver',
country: 'US'
};
}

onUpdateLocation(obj) {
const { city, country } = obj
this.setState({ city, country });
}
}

所以我想知道这两种方式有什么区别?

最佳答案

确实没有:

setState is used internally by Alt to set the state. You can override this to provide your own setState implementation. Internally, setState is an alias for Object.assign. setState must return an object.

http://alt.js.org/docs/createStore/#setstate

一个例子:假设您的州是:

{
city: 'Denver',
country: 'US',
}

更新状态的两种方式:

this.setState({city: 'Colorado Springs'})
console.log(this.state) // {city: 'Colorado Springs', country: 'US' })

this.state = { city: 'Elbert' }
console.log(this.state) // state is {city: 'Elbert'}

如您所见,this.state = 会覆盖状态,而 this.setState() 将新状态合并到旧状态中。请参阅Object.assign()

关于javascript - setState() 对于更新 Alt.js 存储中的状态是可选的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com