setState() 是否可用于更新 Alt.js 商店中的状态?
Is setState() optional for updating the state in Alt.js store?
是的,我知道 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()
是的,我知道 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()