如何使用操作更新reducer状态?

时间:2017-10-27 19:27:44

标签: reactjs react-native redux react-redux

我将动作有效负载传递给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[]之前清除数据。

2 个答案:

答案 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