React-Router with redux-persist



在我的 react 项目中更新了大多数包后,我再也无法弄清楚在使用 connected-react-router 时做了哪些更改以使 redux-persist 工作(从 react-redux-router 更新,现已弃用(。

我尝试在线查看指南,但似乎没有redux-persistconnected-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

要检查的一件事,它可能与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 包装根组件。这会延迟应用 UI 的呈现,直到检索持久状态并将其保存到 redux。

相关内容

  • 没有找到相关文章

最新更新