簡體   English   中英

監聽特定的商店屬性更改

[英]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);
}

我的目標是將Component訂閱到商店的特定屬性。

我試圖讓在檢查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來說明整個問題,但是以下是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM