使用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
与自定义中间件一起使用?
首先,您的商店配置过程是错误的。您拨打applyMiddleware
了不止一次。根据Redux常见问题解答,多次调用会applyMiddleware
设置多个中间件链,这些中间件将无法正常工作。
将其更改为applyMiddleware(axiosMiddleware, thunk)
,然后查看会发生什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句