例如,当前状态为:
{
data: [
{id: 1, number: 100},
{id: 2, number: 200},
{id: 3, number: 300}
]
}
动作是:
const action = (id, number) => {
return {id: id, number: number}
}
如何实现满足以下要求的减速器:
案例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}
]
}
案例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}
]
}
也许它有一个简单的解决方案,但是我找不到解决此问题的正确方法:)另外,我想知道在这种情况下的最佳实践是什么。
提前谢谢
答案 0 :(得分:2)
我将您的操作更改为使用payload
属性,但是如果需要,可以将其删除。 (拥有它更合适)
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}}));
答案 1 :(得分:0)
您如何看待该解决方案?
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;
}
};