React / connected-react-router中的Redux-persist实现

时间:2019-07-18 09:30:39

标签: redux-persist connected-react-router

我实现了redux-persist到connected-react-router。 起初,一切似乎都正常。 Redux存储已连接到本地存储,并保持状态。 但是我意识到,当我打开电子邮件中的链接(http://localhost:9080/reset?token=###来重置密码时,网站只会停留在当前位置。 当我尝试手动更改url时,它不起作用。

链接有效。当我在其他浏览器中打开链接时,它可以工作。 可以手动更改网址,而无需进行redux-persist设置。

store.js

import { applyMiddleware, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';
import { routerMiddleware, connectRouter } from 'connected-react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import rootReducer from './src/reducers';

export const history = createBrowserHistory();
const middlewares = [
  routerMiddleware(history), 
  thunkMiddleware,
  createLogger({
    predicate: () => process.env.NODE_ENV === 'development',
    collapsed: true,
  }),
];
const enhancers = [applyMiddleware(...middlewares)];
const persistConfig = {
  key: 'root',
  storage,
};
const persistedReducer = persistReducer(
  persistConfig,
  rootReducer(history), 
);

export default preloadedState => {
  const store = createStore(
    persistedReducer,
    preloadedState,
    composeWithDevTools(...enhancers),
  );
  const persistor = persistStore(store);

  return { store, persistor };
};

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'connected-react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { PersistGate } from 'redux-persist/lib/integration/react';
import configureStore, { history } from './store';
import Routes from './routes';
import Loading from './src/shared/loading';

const theme = createMuiTheme({
 ...
});
const { store, persistor } = configureStore();
const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store={store}>
    <PersistGate loading={<Loading />} persistor={persistor}>
      <MuiThemeProvider theme={theme}>
        <Router history={history}>
          <Routes />
        </Router>
      </MuiThemeProvider>
    </PersistGate>
  </Provider>,
  root,
);

我尝试过的。

并且我尝试添加“ connectRouter”,如下所示。它似乎并没有改变任何东西。我应该在商店中设置“ connectRouter”吗?

const store = createStore(
  // persistedReducer,
  connectRouter(history)(persistedReducer),
  composeWithDevTools(enhancers),
);

当我使用“ rootReducer”而不是“ rootReducer(history)”时,因为历史将与“ connectRouter(history)(persistedReducer)”重复。它将显示一条错误消息:无法读取未定义的属性“位置”。

"connected-react-router": "^6.4.0"
"redux-persist": "^5.10.0"
"react": "^16.8.6"
"react-dom": "^16.8.6"
"redux": "^4.0.0"

谢谢!!

1 个答案:

答案 0 :(得分:0)

使用不保留黑名单或保留白名单!

constpersistConfig = {   密钥:“ root”,   存储,   黑名单:[“路由器”], };