在更新了我的React项目中的大多数软件包之后,我再也无法弄清使用connected-react-router(从不推荐使用的react-redux-router更新)使redux-persist工作的更改。
我尝试过在线查看指南,但似乎没有一个将redux-persist
与connected-react-router
集成在一起。我该如何使用新的connected-react-router
和这样的设置?
软件包版本:
├── connected-react-router@6.6.0
├── react@16.12.0
├── react-redux@6.0.1
└── redux-persist@6.0.0
src/index.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import './css/index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { PersistGate } from 'redux-persist/integration/react'
import createHistory from 'history/createBrowserHistory'
import { ConnectedRouter } from 'connected-react-router'
import { Provider } from 'react-redux'
import configureStore from './store'
const history = createHistory();
const store = configureStore(history);
ReactDOM.render((
<Provider store={store}>
<ConnectedRouter history={history}>
<App/>
</ConnectedRouter>
</Provider>
), document.getElementById('root'));
registerServiceWorker();
src/store.js
:
import { applyMiddleware, createStore, compose } from 'redux'
import { createFilter } from 'redux-persist-transform-filter';
import { persistReducer, persistStore } from 'redux-persist'
import { routerMiddleware } from 'connected-react-router'
import thunk from "redux-thunk";
import storage from 'redux-persist/lib/storage'
import apiMiddleware from './middleware';
import rootReducer from './reducers'
import createRootReducer from './reducers'
export default (history) => {
const persistedFilter = createFilter(
'auth', ['access', 'refresh']
);
const reducer = persistReducer(
{
key: 'root',
storage: storage,
whitelist: ['auth', 'user', 'game'],
transforms: [ persistedFilter]
},
rootReducer
);
const store = createStore(
createRootReducer(history), {},
compose(
applyMiddleware(thunk, apiMiddleware, routerMiddleware(history)),
window.devToolsExtension ? window.devToolsExtension() : f => f,
),
);
persistStore(store);
return store;
}
src/reducers/index.js
:
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
import auth, * as fromAuth from './auth'
import { reducer as form } from 'redux-form';
const createRootReducer = (history) => combineReducers({
router: connectRouter(history),
auth: auth,
// other reducer stuff
});
export default createRootReducer
答案 0 :(得分:0)
要检查的一件事,可能与PersistGate
有关?
在src/index.js
中,您正在导入PersistGate
,但未使用它。
import { PersistGate } from 'redux-persist/integration/react'
通过使用PersistGate包装您的根组件来尝试使用它。即是这样。
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<ConnectedRouter history={history}>
<App/>
</ConnectedRouter>
</PersistGate>
</Provider>
为此,您需要访问persistor
,这是在调用persistStore(store)
时需要定义的内容。即需要对您的src/store.js
进行一些小的重构。
有关此问题的更多信息,请参见redux-persist的文档。它说...
如果您使用react,请用PersistGate包装您的根组件。这会延迟应用程序用户界面的呈现,直到检索到您的持久状态并将其保存到Redux。