我如何使用Reducer将对象添加到数组中

时间:2019-04-15 16:24:27

标签: javascript arrays reactjs redux immutability

///我需要使用用于联系人簿的reducer将对象添加到数组中

//减速器

const addContact = (contacts = [], action) => {
  let contactsArr = [{}];
  if (action.type = "ADD_CONTACT") {
    return [...contactsArr, action.payload];
  }
  return contacts;
};

动作

export const addContactRed = contact => {
  return {
    type: "ADD_CONTACT",
    payload: contact
  };
};


{
type:"ADD_CONTACT",
payload:{name:"xyz",phonenum:10101001}
}

{
type:"ADD_CONTACT",
payload:{name:"abc",phonenum:0101001}
}

///分派两个动作后,我想要的最终数组是

// contactsArr

[
{name:"xyz",phonenum:10101001},
{name:"abc",phonenum:0101001}
]

1 个答案:

答案 0 :(得分:1)

您没有ton init let contactArr = [{}];它将重置减速器中的储值。只需使用联系人存储变量

const addContact = (contacts = [], action) => {
 // if (action.type = "ADD_CONTACT") {
  if (action.type === "ADD_CONTACT") {
    return [...contacts, action.payload];
  }
  return contacts;
};