我对React和Redux很陌生。我设法用以下命令更新数组中的现有项目
case ACTION_TYPES.SET_PREPARATION_ITEM:
const { id, x, y, rotation } = action.payload;
const currentPreparationItem = state.entity.preparationItems[id];
currentPreparationItem.x = x;
currentPreparationItem.y = y;
currentPreparationItem.rotation = rotation;
return { ...state, preparationItems: { ...state.entity.preparationItems } };
现在我正在尝试使用以下代码将新项目添加到数组中
case ACTION_TYPES.ADD_PREPARATION_ITEM:
const implant: IProductMySuffix = action.payload;
const preparationItem: IPreparationItemMySuffix = {};
preparationItem.x = 10;
preparationItem.y = 10;
preparationItem.productId = implant.id;
preparationItem.image = implant.image;
preparationItem.imageContentType = implant.imageContentType;
const result = { ...state, preparationItems: { ...state.entity.preparationItems.concat(preparationItem) } }
return result;
如果我正确调试,则result
const将具有一个包含一项的数组。但是,在render方法中,似乎无法检测到数组是否包含任何元素。知道是什么原因造成的吗?
添加了部分组件
const mapStateToProps = (storeState: IRootState) => ({
users: storeState.userManagement.users,
customers: storeState.customer.entities,
businesses: storeState.business.entities,
products: storeState.product.entities,
preparationEntity: storeState.preparation.entity,
loading: storeState.preparation.loading,
updating: storeState.preparation.updating,
updateSuccess: storeState.preparation.updateSuccess
});
const mapDispatchToProps = {
getUsers,
getCustomers,
getBusinesses,
getEntity,
getProducts,
updateEntity,
setBlob,
createEntity,
reset,
setPreparationItem,
addPreparationItem
};
答案 0 :(得分:3)
首先,您要更改状态,这违反了redux的规则
case ACTION_TYPES.SET_PREPARATION_ITEM:
const { id, x, y, rotation } = action.payload;
const currentPreparationItem = {...state.entity.preparationItems[id]}; // create a new object instance
currentPreparationItem.x = x;
currentPreparationItem.y = y;
currentPreparationItem.rotation = rotation;
const entity = state.entity ? {...state.entity} : {};
const preparationItems = entity.preparationItems ? [...entity.preparationItems] : [] // Create a new Array instance
preparationItems[id] = currentPreparationItem;
entity.preparationItems = preparationItems;
return {
...state,
entity
};
第二:您正在传播preparationItems
作为对象,但实际上是一个数组(根据您的问题描述)
case ACTION_TYPES.ADD_PREPARATION_ITEM:
const implant: IProductMySuffix = action.payload;
const preparationItem: IPreparationItemMySuffix = {};
preparationItem.x = 10;
preparationItem.y = 10;
preparationItem.productId = implant.id;
preparationItem.image = implant.image;
preparationItem.imageContentType = implant.imageContentType;
const entity = state.entity ? {...state.entity} : {};
// Create a new Array instance and add the new object at the end
entity.preparationItems = entity.preparationItems ? [
...entity.preparationItems,
preparationItem
] : [preparationItem];
const result = {
...state,
entity
}
return result;