combineReducers causes code to break

2019-03-15 03:22发布

问题:

This is subsequent to the thread I posted here

After lot of troubleshooting I found that this code works without any problems

import React from 'react';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import DataTableReducer from './reducers/DataTableReducer';
import DimensionPickerReducer from './reducers/DimensionPickerReducer';

const loggerMiddleware = createLogger();
const store = createStore(
    DimensionPickerReducer, 
    applyMiddleware(
        thunkMiddleware, 
        loggerMiddleware
    )
);

export default store;

But if I replace my single reducer with a combine reducer call like

import React from 'react';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import DataTableReducer from './reducers/DataTableReducer';
import DimensionPickerReducer from './reducers/DimensionPickerReducer';

const loggerMiddleware = createLogger();
const store = createStore(
    combineReducers({
        DataTableReducer,
        DimensionPickerReducer
    }), 
    applyMiddleware(
        thunkMiddleware, 
        loggerMiddleware
    )
);

export default store;

I immediately start getting errors by the DimensionPicker control that the mandatory props were not specified.

So the combineReducer method is not working for me.

I am uploaded a sample project here which shows the problem.

https://github.com/abhitechdojo/MovieLensReact

You will have to run npm install after doing a git clone

回答1:

With combined reducers your store will have data structure like that:

{
    DimensionPickerReducer: {
        dimenisionName: '',
        pickerIsLoading: false,
        pickerError: '',
        currentAttribute: '',
        attributeList: []
    },
    DataTableReducer: {
        tableData: [],
        tableIsLoading:false,
        tableError: ''
    }
}

So you should adjust your containers to work with combined store. For example in DimensionPickerContainer.js you should change mapStateToProps function:

const mapStateToProps = (state) => {
    return {
        attributeList : state.DimensionPickerReducer.attributeList,
        currentAttribute : state.DimensionPickerReducer.currentAttribute
    }
}

You can also name your reduces in store, so they would not look ugly in data structure. E.g. combineReducers({ dimensionPicker: DimensionPickerReducer, dataTable: DataTableReducer})