【问题标题】:Redux Store to subscribe to a particular event only? store.subscribe()Redux Store 仅订阅特定事件? store.subscribe()
【发布时间】:2018-06-06 15:13:35
【问题描述】:

我想将一些用户数据保存到 localStorage,并且需要商店订阅状态更改,但我不想在每次状态更改时触发,而是仅在发生特定事件时触发,例如我的情况user_update 事件。

我可以通过任何方式让商店订阅特定事件而不是通用事件:

store.subscribe(()=>{

//save to local storage here

})

非常感谢您的帮助:)

【问题讨论】:

    标签: reactjs redux local-storage store persist


    【解决方案1】:

    当您订阅商店时,您的内部函数会在每次商店中的某些内容发生变化时触发。这就是它的设计方式。因此,您无法响应事件,但您可以响应商店特定部分的更改。

    function observeStore(store, select, onChange) {
      let currentState;
    
      function handleChange() {
        let nextState = select(store.getState());
        if (nextState !== currentState) {
          currentState = nextState;
          onChange(currentState);
        }
      }
    
      let unsubscribe = store.subscribe(handleChange);
      handleChange();
      return unsubscribe;
    }
    

    然后执行observeStore(store, select, this.writeToLocalStorageOrWhatever)。顺便说一句,要在本地存储中持久存储存储数据,请尝试使用redux-persist

    查看更多信息:Redux store API Discussion

    【讨论】:

    • 随机问题,但是仅在两个状态不同时运行currentState = nextState 有什么好处吗?总是将旧状态换成新状态是否存在性能问题?
    • @samfrances 没有这样的性能问题,但从概念上讲,这个想法是在我们的状态实际改变时改变。同样,如果我们的选择器返回undefined,我们也不会调用该函数。
    【解决方案2】:

    除了订阅特定的事件,你绝对可以只订阅你想要的 reducer 中的特定状态。

    为此,您只需创建单独的商店。

    const store = createStore(combineReducers({
        loginReducer,
        blogReducer
    }))
    export const store1 = createStore(reducer1)
    export const store2 = createStore(reducer2)
    export default store;
    

    然后在你的组件中:

    import store from './store';
    import {store1, store2} from './store';
    
    store.subscribe(() => {
        console.log("subscribe all")
    })
    store1.subscribe(() => {
        console.log("subscribe only states in reducer 1")
    })
    store2.subscribe(() => {
        console.log("subscribe only states in reducer 2")
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      相关资源
      最近更新 更多