redux - reducer状态为空白

sna*_*ies 7 javascript reactjs redux redux-devtools

我试图复制类似于redux docs基本示例中的TodoList 示例.第二个reducer接收一个数组 - styleItems = [{... ... }, {... ...}]然后调用第一个函数来作用于每个单独的对象.

initialState通过以下内容向app容器提供了一个,如图所示containers/app.js.然而,传递给styleItemsreducer 的状态似乎是一个空白数组 - 每次都是如此.

但是,react会根据初始配置呈现UI,并且dev-tools会按预期显示状态结构.redux商店是否会以某种方式看到同样的反应?

集装箱/ app.js

function starterInfo(state) {
    return {

        // The ID of this particular object
        id: 12345,

        // Various keys and theri css values
        styleItems: [
            {
                pk: 31,
                order: 1,
                label: 'Caption text color',
                css_identifier: '.caption-text',
                css_attribute: 'color',
                css_value: '#FFFFFF'
            },
            {
                pk:23,
                order: 2,
                label: 'Caption link color',
                css_identifier: '.caption-link',
                css_attribute: 'color',
                css_value: '#FEFEFE'
            }
        ],

        // Network state info
        currently_fetching: false,
        currently_posting: false
    }
}

export default connect(starterInfo)(App)
Run Code Online (Sandbox Code Playgroud)

减速器/ index.js

// This handles a single styleItem object within the array
function change_css(state = {}, action){
    switch (action.type){
        case actions.CHANGE_CSS:

            if (state.order !== action.order){
                return state
            }

            return {
                ...state,
                css_value
            }

        default:
            return state
    }
}

// This handles the styles array in the global state
function styleItems(state = [], action){
    switch(action.type){       
        case actions.CHANGE_CSS:

            const foobar = state.map(styleItem =>
                change_css(styleItem, action)
                )            

            return foobar

        default:
            return state
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*all 7

简短的回答是你没有完全正确地通过初始状态.connectReact Redux绑定函数的第一个参数是mapStateToProps.此功能的目的是获取应用程序中存在的状态并将其映射到组件的props.你在starterInfo函数中所做的只是硬编码组件的状态.因为你正在返回一个普通对象,React并不真正知道它的区别所以它工作得很好,但是Redux还不知道你的app状态.

相反,你应该做的是直接向reducers提供你的初始状态,如下所示:

const intialStyleItemsState = [
    {
        pk: 31,
        order: 1,
        label: 'Caption text color',
        css_identifier: '.caption-text',
        css_attribute: 'color',
        css_value: '#FFFFFF'
    },
    {
        pk:23,
        order: 2,
        label: 'Caption link color',
        css_identifier: '.caption-link',
        css_attribute: 'color',
        css_value: '#FEFEFE'
    }
];

function styleItems(state = intialStyleItemsState, action){ ...
Run Code Online (Sandbox Code Playgroud)

最后,因为你正在拆分你的减速器,你需要再次使用Redux的combineReducers实用程序将它们组合在一起,将root减速器提供给你的商店并从那里开始.