6

使用 redux-persist 时出现错误。我可以找到一些关于 redux-persist v5 的文档。我只是按照官方的使用示例。但我对此感到困惑。在我使用 redux-persist 之前,我可以正确地从 store 中获取状态。但我想将登录状态保持在本地。所以我尝试使用 redux-persist。然后我遇到了一些问题。这是我的代码:

减速器.js

const initialState = {
  isLogin: false,
  uname: "",
}

const userReducer = (state = initialState, action) => {
  switch(action.type) {
    case 'DO_LOGIN':
      return Object.assign({}, state, {
        isLogin: true,
        uname: action.payload.username
      })
    default:
      return state
  }
}

const reducers = combineReducers({
  userInfo: userReducer
})

export default reducers

store.js

import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import reducers from '../reducers'

const loggerMiddleware = createLogger()

const middleware = [thunk, loggerMiddleware]

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const configureStore = composeEnhancers(
  applyMiddleware(...middleware),
)(createStore)

const config = {
  key: 'root',
  version: 1,
  storage,
}

const combinedReducer = persistCombineReducers(config, reducers)

const createAppStore = () => {
  let store = configureStore(combinedReducer)
  let persistor = persistStore(store)

  return { persistor, store }
}

export default createAppStore

应用程序.js

const mapStateToProps = (state) => ({
  logged: state.userInfo.isLogin
})

当我运行此代码时,我收到此错误消息TypeError: Cannot read property 'isLogin' of undefined 并且控制台中的此错误消息Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

我猜在组合减速器时有些事情是不正确的。但我不知道哪里错了?

4

1 回答 1

9

redux-persist文档中:

import reducers from './reducers' // where reducers is a object of reducers

的第二个参数persistCombineReducers必须是减速器的对象。
yout reducer.js 中的导出应该是:

export default {
  reducer: reducer
};

进行更改并让我知道它是否解决了。

于 2017-11-02T04:47:08.240 回答