如何防止一个javascript对象被转换为一个长度为1的对象数组?

问题描述 投票:0回答:1

我正在做我的第一个单独的ReactJSRedux项目,一切都很顺利,直到我到了一个点,我在Redux存储中使用一个对象,它总是应该是一个单一的对象。当我把这个对象从存储的一个部分(sources键的一个元素)复制到另一个部分(selectedItems键)时,这个对象被存储为一个长度为1的数组,这不是我传递进来的数据(它只是一个单一的对象)。我可以接受这种情况,只需从存储变量中读出一个数组,并只使用元素0,除了当我调用reducer中的另一个方法来替换存储中的那个变量时,该方法将新的数据存储为一个单一的对象! 我的偏好是让所有的东西都存储一个单一对象,但我想不出如何做到这一点。总之,这里是一些reducer的代码。

const initialState = {
    sources: [
        {
            id: 1,
            mfg: 'GE',
            system: 'Smart bed',
            model: '01',
            name: 'GE smart bed'
        },
        {
            id: 2,
            mfg: 'IBM',
            system: 'Patient monitor',
            model: '03',
            name: 'IBM patient monitor'
        }
    ],
    error: null,
    loading: false,
    purchased: false,
    selectedItem: {}
};

// This is called when a user selects one of sources in the UI
// the Id of the selected sources object is passed in as action.id
// This method creates an array in state.selectedItem 
const alertSourceSelect = ( state, action ) => {
    let selectedItem = state.sources.filter(function (item) {
        return item.id === action.id;
    });

    if (!selectedItem) selectedItem = {};
    return {...state, selectedItem: selectedItem};
};

// When someone edits the selected source, this takes the field name and new value to 
// replace in the selected source object and does so. Those values are stored in 
// action.field and action.value . However, when the selected source object is updated
// it is updated as a single object and not as an array.
const selectedSourceEdit = ( state, action ) => {
    return {
        ...state,
        selectedItem: updateObject(state.selectedItem[0], { [action.field] : action.value })
    };
};

const reducer = (state = initialState, action) =>  {
        switch (action.type) {
        case actionTypes.ALERT_SOURCE_SELECT: return alertSourceSelect( state, action );
        case actionTypes.ALERT_SELECTED_SOURCE_EDIT: return selectedSourceEdit( state, action );
        default: return state;
    }

这里是updateObject方法(抱歉我漏掉了):

export const updateObject = (oldObject, updatedProperties) => {
    return {
        ...oldObject,
        ...updatedProperties
    }
};
javascript arrays reactjs react-redux
1个回答
0
投票

问题: updateObject 返回的是对象而不是数组,而且你在维护一个对象。selectedItem 作为数组而非对象

export const updateObject = (oldObject, updatedProperties) => {
    return {
        ...oldObject,
        ...updatedProperties
    }
};

解决方案 :

要不就从 updateObject :

export const updateObject = (oldObject, updatedProperties) => {
    return [{
        ...oldObject,
        ...updatedProperties
    }]
};

或将返回的对象组成数组

const selectedSourceEdit = ( state, action ) => {
    return {
        ...state,
        selectedItem: [updateObject(state.selectedItem[0], { [action.field] : action.value })]
    };
};
© www.soinside.com 2019 - 2024. All rights reserved.