Javascript React redux:更新数组中的值
作为初始状态,我使用对象数组:Javascript React redux:更新数组中的值,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,作为初始状态,我使用对象数组: export default{ items: [ { Date: 1, Operation: 'revenue', } ] } 在组件中,我分派操作,该操作必须更新数组对象中的一个元素:“Operation” 减速器: import initialState from '../constants/initialState'; impo
export default{
items: [
{
Date: 1,
Operation: 'revenue',
}
]
}
在组件中,我分派操作,该操作必须更新数组对象中的一个元素:“Operation”
减速器:
import initialState from '../constants/initialState';
import { app } from '../constants/types';
export default function update(state = initialState, action) {
switch (action.type) {
case app.SELECT:
return {
...state,
[action.payload.key]: state.items.map(
(item, i)=> i===0 ? {...item, Operation: action.payload.value}
: item
)
};
default:
return state;
}
}
但是,当我选择新值和应用程序运行handleChange、分派操作、运行reducer时,存储中的状态将保留旧值“Operation”
我做错了什么?我想这就是你需要做的: 首先将
id属性
添加到项目
,然后执行以下操作:
export default {
items: [
{
id: 0,
Date: 1,
Operation: "revenue",
},
],
};
问题在于我没有更新数组的状态。 这是一个工作代码:
export default function update(state = initialState, action) {
switch (action.type) {
case app.SELECT:
return {
...state,
items: state.items.map(
(item, i)=> i===0 ? {...item, [action.payload.key]: action.payload.value}
: item
)
};
default:
return state;
}
}
在前面的返回块中,我使用了[action.payload.key],其中应该使用“items”。因此,我更新了“操作”,其中“项目”已更新。您的项目必须具有唯一的
键或id
,以便您可以选择它们,然后更新它们。您是否尝试了console.log有效负载发送到应用程序。选择操作?什么是有效载荷?您的减速器不会更改您状态的项属性,而是操作.payload.key
属性(在本例中为操作
)Cường Mạ新罕布什尔州恩圭ễn、 使用“console.log(items=${JSON.stringify(this.props.itemsProp)}
);”在handleChange方法中,我看到了“items=[{“Date”:1,“Operation”:“revenue”}]”phtrivier,您是对的。这就是问题的根源。考虑到我的问题,我给出了答案。
class OperationSelect extends React.Component {
// constructor
handleChange(event) {
this.props.selectOperation({
key: "Operation", // I think you need to check this and try to findout that you need this or not
value: event.target.value,
id: 0 // 0 is just an example you need to decide how you would implement the id
});
}
// render() logic
}
export default function update(state = initialState, action) {
switch (action.type) {
case app.SELECT:
return {
...state,
items: state.items.map((item, i) =>
i === action.payload.id ? { ...item, Operation: action.payload.value } : item
),
};
default:
return state;
}
}
export default function update(state = initialState, action) {
switch (action.type) {
case app.SELECT:
return {
...state,
items: state.items.map(
(item, i)=> i===0 ? {...item, [action.payload.key]: action.payload.value}
: item
)
};
default:
return state;
}
}