[英]How to update state (array of objects) with incoming object in Redux?
For example, current state is:例如,当前状态是:
{
data: [
{id: 1, number: 100},
{id: 2, number: 200},
{id: 3, number: 300}
]
}
Action is:行动是:
const action = (id, number) => {
return {id: id, number: number}
}
How to implement reducer that it meets the following requirements:如何实现满足以下要求的reducer:
CASE 1:情况1:
//incoming object
{id: 4, number: 400}
//result
{
data: [
{id: 1, number: 100},
{id: 2, number: 200},
{id: 3, number: 300},
{id: 4, number: 400}
]
}
CASE 2:案例2:
//another incoming object
{id: 2, number: 250}
//result
{
data: [
{id: 1, number: 100},
{id: 2, number: 250},
{id: 3, number: 300},
{id: 4, number: 400}
]
}
Maybe it has a simple solution, but I can't find the right approach to solving this problem:) Also I would like to know what is the best practice in cases like this.也许它有一个简单的解决方案,但我找不到解决这个问题的正确方法:) 另外我想知道在这种情况下的最佳实践是什么。
Thank you in advance先感谢您
I changed your action to use the payload
property, but if you want you can remove it.我将您的操作更改为使用payload
属性,但如果您愿意,可以将其删除。 (It's more proper to have it) (拥有它更合适)
const reducer = (state, action) => { switch(action.type) { case 'UPDATE_OR_INSERT': return { data: [ ...state.data.filter(x => x.id !== action.payload.id), action.payload, ] } default: } return state; } console.log( reducer({ data: [ {id: 1, number: 100}, {id: 2, number: 200}, {id: 3, number: 300}, {id: 4, number: 400} ] }, { type: 'UPDATE_OR_INSERT', payload: {id: 2, number: 250}}));
How do you think of this solution?您如何看待这个解决方案?
const testState = {
data: []
}
export default (state = testState, action) => {
switch(action.type){
case "SET_DATA":
return [
...state.data.filter(d => d.id !== action.payload.id),
action.payload,
];
default:
return state;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.