![](/img/trans.png)
[英]How to prevent an array of unit length in POST body from being converted to a string?
[英]How do you prevent a javascript object from being converted into a length 1 array of objects?
我正在处理我的第一个单独的 ReactJS/Redux 项目,事情进展顺利,直到我在 Redux 商店中使用 object 时,它总是应该是一个单一的 ZA8CFDE6331BD4B66AC96F8911C。 当我将 object 从存储的一部分(源键的一个元素)复制到另一部分(selectedItems 键)时,object 被存储为长度为 1 的数组,这不是我传入的数据(它只是一个对象)。 我可以忍受这一点,只需将该存储变量作为数组读出,然后只使用元素 0,除非当我在 reducer 中调用另一个方法来替换存储中的该变量时,该方法将新数据存储为单个 object。 我的偏好是让所有东西都存储一个 object 但我不知道该怎么做,无论如何:这是一些减速器代码:
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
}
};
问题: updateObject
返回 object 而不是数组,并且您将selectedItem
维护为数组而不是 object
export const updateObject = (oldObject, updatedProperties) => {
return {
...oldObject,
...updatedProperties
}
};
解决方案:
从updateObject
返回数组:
export const updateObject = (oldObject, updatedProperties) => {
return [{
...oldObject,
...updatedProperties
}]
};
或制作返回的 object 数组
const selectedSourceEdit = ( state, action ) => {
return {
...state,
selectedItem: [updateObject(state.selectedItem[0], { [action.field] : action.value })]
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.