无法使React-redux与redux-persist一起使用

时间:2017-12-21 17:07:30

标签: javascript react-redux redux-persist

您好我正在尝试使用react-redux设置redux-persist,但我无法让它工作。我收到以下错误:

  

TypeError:_store2.default不是函数[了解更多] index.js:12:29

我现在如何设置:

store.js

import {applyMiddleware, createStore} from 'redux';
import {persistStore,persistCombineReducers} from 'redux-persist';
import storage from 'redux-persist/es/storage' // default: localStorage if web, AsyncStorage if react-native

import { logger } from 'redux-logger';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import reducer from './reducers'

const middleware = applyMiddleware(promise(), thunk, logger);

const config = {
  key: 'root',
  storage,
};

const reducers = persistCombineReducers(config, {reducer});

export const configureStore = () => {
  const store = createStore(reducers, middleware);
  const persistor = persistStore(store);
  return { persistor, store };
};

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import './css/app.css';
import App from './containers/App';

import { PersistGate } from 'redux-persist/es/integration/react'
import configureStore from './store';
const { persistor, store } = configureStore()


ReactDOM.render(
  <Provider store={store} >
    <PersistGate persistor={persistor}>
    <BrowserRouter>
      <App/>
    </BrowserRouter>
  </PersistGate>
  </Provider>,
  document.getElementById('root')
);

更新1

根据@ azium的回复,我得到:

  

组件中出现上述错误:       在Connect(App)中(由Route创建)       在Route中(由withRouter创建(Connect(App)))       in withRouter(Connect(App))       在路由器中(由BrowserRouter创建)       在BrowserRouter中       在PersistGate中       在提供者

从App.js中调用它时如此:

@withRouter
@connect((store) => {
  return {
    isAuthenticated: store.auth.isAuthenticated,
  };
})

2 个答案:

答案 0 :(得分:2)

如果您想使用默认导出,则需要更改:

export const configureStore = () => {
  const store = createStore(reducers, middleware);
  const persistor = persistStore(store);
  return { persistor, store };
};

到:

export default () => {
  const store = createStore(reducers, middleware);
  const persistor = persistStore(store);
  return { persistor, store };
};

或:

const configureStore = () => {
  const store = createStore(reducers, middleware);
  const persistor = persistStore(store);
  return { persistor, store };
};

export default configureStore;

或者如果您不想使用默认导出更改:

import configureStore from './store';

为:

import { configureStore } from './store';

答案 1 :(得分:0)

因此,经过一些思考和社区帮助,我设法将问题缩小到我的减速器声明。我用combineReducers声明了index.js中的reducer,而redux-persist说它不应该。

最终index.js代码:

import user from './userReducer'
import auth from './authReducer'

export default ({
  user, auth
})