首页 > 解决方案 > 如何防止 javascript 对象被转换为长度为 1 的对象数组?

问题描述

我正在处理我的第一个单独的 ReactJS/Redux 项目,一切进展顺利,直到我在 Redux 存储中使用一个始终应该是单个对象的对象。当我将对象从存储的一部分(源键的一个元素)复制到另一个(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
    }
};

标签: javascriptarraysreactjsreact-redux

解决方案


问题: 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 })]
    };
};

推荐阅读