[英]Listen for a specific Store property change
I have a Component which initial state is set to be equal to a Store state. 我有一个组件,其初始状态设置为等于存储状态。 Also the Component is subsribed to any change that occurs in the Store.
此外,组件也应适用于商店中发生的任何更改。
// Inital component's state is set to be equal to a Store state
constructor(props) {
super(props);
this.state = EntityStore.getState();
this.entitiesOnChange = this.entitiesOnChange.bind(this);
}
// Subscribe to any Store's change
componentDidMount() {
EntityStore.listen(this.entitiesOnChange);
}
// Update the state with the new one
entitiesOnChange(nextState) {
this.setState(nextState);
}
My goal is to subscribe the Component to a specific property of the Store. 我的目标是将Component订阅到商店的特定属性。
I tried to make a check in entitiesOnChange
, but I find out that this.state
is already up to date with the Store's state ( nextState
). 我试图让在检查
entitiesOnChange
,但我发现, this.state
已经是最新的与存储的状态( nextState
)。 Also in the following code example (what I tried) this.setState(nextState)
isn't called, because the both states are equal, therefore rerendering doesn't occur: 同样在以下代码示例(我尝试过)中,未调用
this.setState(nextState)
,因为两个状态相等,因此不会发生重新渲染:
// Update the state with the new one only if a specefic `propery` is changed
entitiesOnChange(nextState) {
// Here is the problem. `this.state` is already up to date.
if (this.state.property !== nextState.property) {
this.setState(nextState);
}
}
So how can I subscribe my Component to a specific Store's property? 那么,如何才能将我的组件订阅到特定商店的属性?
Alright! 好的! I deeply investigated the problem and finaly I've find out what's happening.
我对问题进行了深入调查,并最终确定了所发生的情况。 The problem was caused by a wrong way of setting the data in the store.
该问题是由在存储中设置数据的错误方式引起的。 It was mutated (which is wrong).
它被突变了(这是错误的)。 The correct (flux) way is creating a new object.
正确的(通量)方法是创建一个新对象。
I've created a JSFiddle to illustrate the whole problem, but here are the highlights of the wrong mutation in the Store: 我创建了一个JSFiddle来说明整个问题,但是以下是Store中错误突变的要点:
class Store {
constructor() {
this.bindActions(actions);
this.data = {
items: [],
isLoading: false
};
}
set(items) {
this.data.isLoading = true;
// Simulate API call
setTimeout(() => {
this.data.items = items;
this.data.isLoading = false;
this.setState(this);
}, 2000);
this.setState(this);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.