如何使用redux-persist v5?

时间:2017-11-01 08:02:00

标签: reactjs redux redux-persist

我开始学习redux并尝试使用redux-persist来存储数据。由于redux-persist现在更新到v5并建议使用PersistGate。但是我找不到关于PersistGate的文章。我写了一些代码,但发生了这个错误PersistGate(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.这是我的代码:

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 reducer 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',
  storage,
}

const combinedReducer = persistCombineReducers(config, reducer)

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

  return { persistor, store }
}

export default createAppStore

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './assets/css/index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { Provider } from 'react-redux'
import createAppStore from './store'
import { PersistGate } from 'redux-persist/es/integration/react'

const { persistor, store } = createAppStore()

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

编译器在render()中抛出错误。上面的错误信息。 你能告诉我如何正确使用PersistGate吗?或者我在哪里可以找到更多文档或示例?非常感谢你!

2 个答案:

答案 0 :(得分:4)

如果添加加载状态<Loading />(它是像spinner或greeking组件那样的组件,它定义了应用程序在从存储中加载数据时的外观)PersistGate仍无法正常工作。

请确认您的减速机 import reducer from '../reducers',应该是原始的reducer(javascript对象),不要应用combineReducers(redux),如果你已经应用了它,那么在你的store.js中,你应该使用persistReducer而不是persistCombineReducers如下

import { persistReducer } from 'redux-persist'
...
...
const combinedReducer = persistReducer(config, reducer)
...
...

可能有助于解决问题,如果没有,请留言

答案 1 :(得分:0)

我知道原因。在v5.2.0中需要加载。像这样:

render() {
  return (
    <PersistGate 
      persistor={persistor} 
      loading={<Loading />}
      >
    <PersistGate persistor={persistor}>
      {/* rest of app */}
    </PersistGate>
  )
}

现在在v5.2.2

中是可选的