侦听特定商店 属性 的变化
Listen for a specific Store property change
我有一个初始状态设置为等于存储状态的组件。此外,组件会订阅商店中发生的任何更改。
// 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);
}
我的目标是将组件订阅到商店的特定 属性。
我试图检查 entitiesOnChange
,但我发现 this.state
已经与商店的状态 (nextState
) 保持同步。同样在以下代码示例中(我尝试过的) 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);
}
}
那么我如何才能将我的组件订阅到特定商店的 属性?
好的!我深入调查了这个问题,最后我发现了发生了什么。问题是由于在商店中设置数据的错误方式引起的。它被变异了(这是错误的)。正确的(通量)方法是创建一个新对象。
我创建了一个 JSFiddle 来说明整个问题,但这里是商店中错误突变的亮点:
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);
}
}
我有一个初始状态设置为等于存储状态的组件。此外,组件会订阅商店中发生的任何更改。
// 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);
}
我的目标是将组件订阅到商店的特定 属性。
我试图检查 entitiesOnChange
,但我发现 this.state
已经与商店的状态 (nextState
) 保持同步。同样在以下代码示例中(我尝试过的) 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);
}
}
那么我如何才能将我的组件订阅到特定商店的 属性?
好的!我深入调查了这个问题,最后我发现了发生了什么。问题是由于在商店中设置数据的错误方式引起的。它被变异了(这是错误的)。正确的(通量)方法是创建一个新对象。
我创建了一个 JSFiddle 来说明整个问题,但这里是商店中错误突变的亮点:
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);
}
}