我将动作有效负载传递给reducer并希望reducer更新相应的data
并返回整个状态。
减速机:
const initialState = {
fname: 'FNAME',
lname: 'LNAME',
data: []
}
const DATA1 = [
{id:1, name:'D1a'},
{id:2, name:'D1b'}
]
const DATA2 = [
{id:1, name:'D2a'},
{id:2, name:'D2b'}
]
export default function peopleReducer(state=initialState, action){
console.log(action.payload);
switch(action.payload){
case "case1":
return {...state, DATA1}; // how do I code this?
case "case2":
return {...state, DATA2};
default:
return state
}
}
如何根据state.data
设置action.payload
?
我试过了:
case "case1":
return {
...state,
data: [...state.data, ...DATA1]
};
但它不断追加数据。我希望在使用点差运算符...DATA1
并将其推送到data[]
之前清除数据。
答案 0 :(得分:0)
您可以像这样替换data属性的内容:
return {...state, data: DATA1}
state
已经有data
属性,但它将被稍后发生的data属性覆盖。
答案 1 :(得分:0)
您应该启用操作类型,而不是有效负载。在您的情况下,操作类型将是"案例1","案例2"等。
您可以通过解构type BlahType = {
blah: string,
...rest: Array<string>, // this is what I would expect to be able to do
};
const myFunction = (blah: string, ...args: Array<string>): BlahType => {
const otherConstants = args.reduce(
(obj, arg) => Object.assign(obj, { [arg]: arg }),
{},
);
return {
BLAH_CONSTANT: blah,
...otherConstants,
};
};
并将data
元素替换为新的state
来替换data
元素。
你的减速器看起来像
DATA1