redux-persist合并reducer时报错

问题描述

报错信息:

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

问题出现的环境背景及自己尝试过哪些方法

我将不同功能的reducer放到不同的文件夹下,然后使用redux-persist进行数据持久化处理,web项目会经常刷新么,所以想让store中的数据不丢失,然而合并reducer应用combineReducers方法是报错,不知道为什么

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
reducer

import * as Pages from './action-types';

let defaultValue = {
    user_name: "",
    user_id: ""
}

export default function UserInfo (state = defaultValue, action = {}) {
    switch (action.type) {
        case Pages.SAVEUSERINFO:
            return { ...state,
                ...{
                    user_name: action.data.data.username,
                    user_id: action.data.data.id
                }
            };
        default:
            return state;
    }
}

合并位置

import {
    combineReducers,
} from 'redux';
import UserInfo from './Pages/reducers';
import SaveInfo from './Layout/reducers';


const rootReducer = combineReducers({ 
    UserInfo,
    SaveInfo
});

export default rootReducer;

入口文件

import {
    Provider
} from 'react-redux';
import {
    createStore,
    applyMiddleware
} from 'redux';
// 这个Reducers就是我合并的reducer
import Reducers from '@/Reducers';
import thunk from 'redux-thunk';
import {persistStore, persistCombineReducers} from 'redux-persist';
import { PersistGate } from 'redux-persist/es/integration/react';

import storage from 'redux-persist/es/storage'
const config = {
    key: 'root',
    storage,
};

function configureStore(){
    console.log(Reducers)
    let reducer = persistCombineReducers(config, Reducers);
    let store = createStore(reducer, applyMiddleware(thunk));
    let persistor = persistStore(store);
    return { persistor, store }
}
const render = Component => {
    const { persistor, store } = configureStore();
    ReactDOM.render(
        //绑定redux、热加载
        <Provider store={store}>
            <PersistGate persistor={persistor}>
                <Component />
            </PersistGate>
        </Provider>,
        document.getElementById('app'),
    )
}

你期待的结果是什么?实际看到的错误信息又是什么?

期待无论怎么刷新浏览器,刷新之前的store中的数据能保存到刷新之后来

阅读 6.6k
2 个回答

persistCombineReducers这个方法不知道是我用的不对还是被官方废弃了,看文档使用persistReducer方法来合并config和reducer即可完成实现

import { persistStore, persistReducer } from 'redux-persist';
const persistedReducer = persistReducer(persistConfig, Reducers)
function configureStore(){
    let store = createStore(persistedReducer, applyMiddleware(thunk));
    let persistor = persistStore(store);
    return { persistor, store }
}
const render = Component => {
    const { persistor, store } = configureStore();
    ReactDOM.render(
        //绑定redux、热加载
        <Provider store={store}>
            <PersistGate persistor={persistor}>
                <Component />
            </PersistGate>
        </Provider>,
        document.getElementById('app'),
    )
}

哪位大神如果有具体的问题原因也烦请告知一下,感激不尽

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题