4

使用 redux-persist 5.10.0。

使用官方文档对其进行配置后,它运行良好:

// configureStore.js
// all imports here

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['auth']
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export default function configureStore() {
    const store = createStore(
        persistedReducer,
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
        applyMiddleware(axiosMiddleware),
        applyMiddleware(thunk)
    );

    const persistor = persistStore(store);

    return { store, persistor };
}

和:

// index.js
// All imports here

const { store, persistor } = configureStore();

ReactDOM.render(
    <Provider store={ store }>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.getElementById('root')
);

正如您从我的 configureStore.js 文件中看到的那样,我有一个用于 axios 的自定义中间件。我正在使用 JWT 进行身份验证。该中间件将检查一个名为的操作常量RECEIVE_LOGIN,以便它可以将返回的令牌分配给我的 axios 实例的默认标头:

// axiosConfig.js
// imports here
export const axiosMiddleware = ({ dispatch, getState }) => next => action => {
    if (action.type === 'RECEIVE_LOGIN') {
        axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${action.data.token}`;
    }

    return next(action);
}

但是由于 redux-persist,我无法从 action.type 中获取我的自定义类型 - RECEIVE_LOGIN - 我得到的是persist/PERSIST,然后是persist/REHYDRATE。我什至找不到我的自定义类型action

我查了一下,但找不到任何带有自定义中间件的示例。

所以我的问题是,如何redux-persist与自定义中间件一起使用?

4

1 回答 1

3

作为第一个问题,您的商店配置过程是错误的。你applyMiddleware不止一次打电话。根据 Redux FAQ,多次调用applyMiddleware会设置多个中间件链,这将无法正常工作

将其更改为applyMiddleware(axiosMiddleware, thunk),然后看看会发生什么。

于 2018-06-14T21:48:38.020 回答