首页 > 解决方案 > 通过全局变量反应互斥锁

问题描述

我们正在使用ReactRedux
我们如何在互斥锁的帮助下保护资源不被访问?

可以通过全局变量以及将它们存储在哪里来做到这一点吗?
PS 由于状态更新延迟,我们不想通过 Redux 执行此操作

提供更多上下文的小例子

export default function configureStore() {
  const store = createStore(rootReducer, persistedState, composedEnhancers);
  store.subscribe(
    // saveState saves state to localStorage
    // here we need mutex which will prevent state from saving to localStorage
    // and some way to toggle this mutex
    throttle(() => {
      saveState(store.getState());
    }, 2000),
  );
  return store;
}

标签: javascriptreactjsconcurrencymutex

解决方案


我不确定这是否是正确的解决方案
请记住,这是可行的,因为store.subscribe会监听 redux 状态更改

export default function configureStore() {
  const store = createStore(rootReducer, persistedState, composedEnhancers);
    store.subscribe(
      throttle(() => {
        const currentState = store.getState();
        // if we allowing state to sync with localStorage
        if (currentState.isMutexVariable) {
          saveState(currentState);
        }
      }, 2000),
    );
  return store;
}

推荐阅读