我尝试使用React在对象数组中增加数量属性。 但是我不知道如何才能更新该项目。
我尝试过的事情:
const initialState = {
items: [{
id: 254,
quantity: 1
},
{
id: 493,
quantity: 1
}
],
};
const payload = {
id: 254
};
function updateProduct(state, action) {
return state.items.map((item, i) => {
if (item.id === action.id) {
return {
...state,
items: [
...state.items,
{
[i]: {
quantity: state.items[i].quantity + 1
}
}
]
};
}
});
}
返回的对象应该是:
{
items: [{
id: 254,
quantity: 2
},
{
id: 493,
quantity: 1
}
],
}
感谢您的帮助!
答案 0 :(得分:1)
好像您在那儿挖了一点深。根据您提供的数据,这不是那么简单:
function updateProduct(state, action) {
return state.items.map((item, i) => {
if (item.id === action.id) {
return {
...item,
quantity: item + 1
}
} else {
return item
}
});
}
答案 1 :(得分:1)
我将建议一些更改:
因此产生:
const reducer = (state, action) => {
const {type, payload} = action;
switch(type) {
case 'update_quantity':
const {id: itemId, quantity} = payload
return ({
...state,
items: state.items.map(item => (item.id === itemId ? {...item, quantity} : item)
default:
return state;
}
}
然后更新:
dispatch({type: 'update_quantity', payload: {id: 'xxx', quantity: 3}});
答案 2 :(得分:0)
首先,您必须将arr状态/值克隆/存储在新变量中
let state = [...initialState.items] // now you have all the values in state var
// and then mutate the state
let mutatedState = state.map(el => {
//modify data how you need
});
// Then assign mutatedState to initialState.items
initialState.items = mutatedState
};
答案 3 :(得分:0)
假设您要
{
items: [{
id: 254,
quantity: 2
},
{
id: 493,
quantity: 2 // <<<<<<<<<<<< 2 here as well
}
],
}
,并假设您可以使用最新的ECMA脚本和最好的ECMA脚本:
const initialState = {
items: [{
id: 254,
quantity: 1
},
{
id: 493,
quantity: 1
}
],
};
const reduceIncrementQuantity = (item) => ({...item, quantity: item.quantity + 1});
const reduceIncrementQuantities = (state) => ({items: state.items.map(reduceIncrementQuantity)});
console.log(reduceIncrementQuantities(initialState));
答案 4 :(得分:0)
解决方案:
为简单起见,请深度克隆对象(状态)并递增指定的值。
const initialState = {
items: [{
id: 254,
quantity: 1
},
{
id: 493,
quantity: 1
}
],
};
const payload = {
id: 254
};
console.log (updateProduct(initialState, payload));
function updateProduct(state, action) {
var newState = JSON.parse(JSON.stringify(state));
var isFound = false;
newState.items.forEach(item => {
for (var prop in item) {
if (prop === 'id' && item[prop] == action.id) {
item.quantity++; isFound = true; break;
}
}
if (isFound) return;
});
return newState;
}
答案 5 :(得分:0)
您可以这样写,
function updateProduct(state, action) {
return { ...state,
items: state.items.map(item => ({
...item,
quantity: action.id === item.id ? item.quantity + 1 : item.quantity
}))
}
}
答案 6 :(得分:0)
这是我通常如何更新Redux存储阵列中的项目 您可以这样做:
function updateProduct(state, action) {
let updatedItems = state.items.map((item)=>{
if(item.id=== action.id){
return {...item,quantity:item.quantity+1}
}
return item
})
return {...state, items:updatedItems}
}