2

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

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

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

4

2 回答 2

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 的回答

于 2019-12-02T08:50:44.407 回答
0

试试这个中间件:

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 并在之后取消订阅。

于 2018-03-30T11:54:38.610 回答