combineReducers导致代码中断

时间:2016-02-15 05:56:15

标签: reactjs redux react-redux

这是我发布here

的帖子的后续内容

经过大量的故障排除后,我发现此代码没有任何问题

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;

但是,如果我用像

这样的联合减速器调用替换我的单个减速器
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;

我立即开始通过DimensionPicker控件获取未指定强制道具的错误。

所以combineReducer方法对我不起作用。

我上传了一个展示问题的示例项目。

https://github.com/abhitechdojo/MovieLensReact

执行git clone

后,您必须运行npm install

1 个答案:

答案 0 :(得分:31)

使用组合缩减器,您的商店将具有以下数据结构:

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

因此,您应该调整容器以使用组合存储。例如,在DimensionPickerContainer.js中,您应该更改mapStateToProps功能:

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

您还可以在商店中命名您的简化,因此它们在数据结构中看起来不会很难看。例如。 combineReducers({ dimensionPicker: DimensionPickerReducer, dataTable: DataTableReducer})