是的,我知道 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 });
}
}
所以我想知道两种方式的区别是什么?
答案 0 :(得分:3)
没有,真的:
setState在内部由Alt用于设置状态。您可以覆盖它以提供您自己的setState实现。在内部,setState是Object.assign的别名。 setState必须返回一个对象。
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()