【问题标题】:React Redux - how to trigger action after another action without ComponentReact Redux - 如何在没有组件的另一个动作之后触发动作
【发布时间】:2018-09-08 15:57:39
【问题描述】:

我正在使用 react-persist 将 redux 状态保存到本地存储。

我想根据持久化状态进行 api 调用,所以我想在操作 persist/REHYDRATE(由库定义并自行执行)发生后立即调度请求调用。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 你想要这样的东西吗? stackoverflow.com/a/49540589/7060441
  • @devserkan 不,我已经使用 redux thunk 发出批处理请求。我想要做的是在发生不受我控制的库的动作时触发动作。
  • 哦,我现在明白了。抱歉误导。

标签: reactjs redux react-redux redux-persist


【解决方案1】:

发布的答案有错误,所以我想改进错误的答案: 根据问题“我想在动作持续/再水化之后立即发送请求调用”。

import {API_CALL} from "./ACTION/API/index"


let hasRehydrated = false;

const onRehydrationMiddleware = store => next => action => {
    // if this Action happens to be 'persist/REHYDRATE' then follow it up with your 
    // desired Action
    if (!hasRehydrated && action.type === 'persist/REHYDRATE') {
        hasRehydrated = true;
        next(action); // this is to make sure you get the Rehydrated State before making                                 
                      // the store.dispatch(API_CALL()) call
        store.dispatch(API_CALL()); //
    } else {
        // make a call to the next action
        next(action);
    }
};

感谢 timotgl 的回答

【讨论】:

    【解决方案2】:

    试试这个中间件:

    let hasRehydrated = false;
    
    const onRehydrationMiddleware = store => next => action => {
        if (!hasRehydrated && action.type === 'persist/REHYDRATE') {
            hasRehydrated = true;
            store.dispatch(callApi());
        } else {
            next(action);
        }
    };
    

    您可能不需要记住 persist/REHYDRATE 之前是否已经发送过(我不确定它是否只发生过一次),在这种情况下只需删除标志即可。否则它会记住中间件所在的模块范围内的事件,这可以作为穷人的单例模式正常工作。

    在这个事件之后基本上不再需要中间件,但我认为创建商店后不可能将它们扔掉。您可以使用store.subscribe(listener),但侦听器看不到操作。另一种选择是根据状态检测补液是否发生,我假设状态会以某种方式发生变化。然后 store.subscribe 就可以工作了,你可以调用 api 并立即取消订阅。

    【讨论】:

      猜你喜欢
      • 2016-10-02
      • 1970-01-01
      • 2019-08-21
      • 2018-05-15
      • 2017-05-14
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多