使用 connect 与 react-redux 和 redux-persist
Posted
技术标签:
【中文标题】使用 connect 与 react-redux 和 redux-persist【英文标题】:Using connect with react-redux and redux-persist 【发布时间】:2018-06-06 21:39:50 【问题描述】:我的 react-redux 和 redux-persist 设置出现以下错误:
上述错误发生在组件中:在Connect(App)中(由 Route) in Route (由 withRouter(Connect(App))) 中创建 在Router(由BrowserRouter创建)中的withRouter(Connect(App)) Provider中PersistGate中的BrowserRouter
我是这样设置的:
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')
);
App.js
import React from 'react'
import withRouter, Switch, Route from 'react-router-dom'
import connect from 'react-redux'
...
@withRouter
@connect((store) =>
return
isAuthenticated: store.auth.isAuthenticated,
;
)
export default class App extends React.Component
render()
...
更新 1
完整的控制台日志
更新 2
这是声明reducer的正确方法吗?没有 redux-persist 也能正常工作
authReducer.js
export default function reducer(state =
isAuthenticated: false
, action)
...
更新 3
REHYDRATE 控制台日志
更新 4
index.js(在 reducers 文件夹中)
import combineReducers from 'redux';
import user from './userReducer';
import auth from './authReducer';
export default combineReducers(
user,
auth
)
【问题讨论】:
你的 app.js 似乎被截断了或者什么的...... 我更新了它,但我认为问题不在于缺少的代码.. 也许它在控制台中指定了有关错误的更多详细信息?我想应该有第二条消息 @DanielKhoroshko 添加了完整日志 auth reducer 好像丢失了初始状态? 【参考方案1】:所以问题是一个人不应该同时使用 combineReducers 和 persistCombineReducers。类似的情况可以在这里找到https://github.com/rt2zz/redux-persist/issues/516
【讨论】:
以上是关于使用 connect 与 react-redux 和 redux-persist的主要内容,如果未能解决你的问题,请参考以下文章
React×Redux——react-redux库connect()方法与Provider组件
React-redux @connect 不起作用,但 connect() 可以