gpt4 book ai didi

reactjs - 如何使用 redux-persist v5?

转载 作者:行者123 更新时间:2023-12-03 14:09:00 25 4
gpt4 key购买 nike

我开始学习redux并尝试使用redux-persist来存储数据。由于 redux-persist 现在已更新到 v5,建议使用 PersistGate。但我找到的关于PersistGate的文档很少。我编写了一些代码,但发生了此错误 PersistGate(...): 渲染没有返回任何内容。这通常意味着缺少返回语句。或者,不渲染任何内容,返回 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吗?或者在哪里可以找到更多文档或示例?非常感谢!

最佳答案

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

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

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

或许可以帮助解决问题,如果不行请留言

关于reactjs - 如何使用 redux-persist v5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com