使用 redux-persist 5.10.0。
使用 official documentation 配置后它运行良好:
// 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
的 Action 常量。因此它可以将返回的 token 分配给我的 axios 实例的默认 header :// 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
与我的自定义中间件一起?
最佳答案
首先,您的商店配置过程是错误的。您正在调用 applyMiddleware
不止一次。根据 Redux 常见问题解答,calling applyMiddleware
multiple times sets up multiple middleware chains, which won't work correctly .
改成applyMiddleware(axiosMiddleware, thunk)
,然后看看会发生什么。
关于reactjs - 如何将 redux-persist 与自定义中间件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50865397/