Redux Store 仅订阅特定事件? store.subscribe()

Redux Store to subscribe to a particular event only? store.subscribe()

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

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

store.subscribe(()=>{

//save to local storage here

})

非常感谢您的帮助:)

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

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

除了订阅特定事件,你绝对可以只订阅你想要的 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")
})