我如何使用reducer将对象添加到数组中
How can i add objects into array using reducer
//我需要使用 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}
}
//分派两个动作后我想要的最终数组是
//联系方式
[
{name:"xyz",phonenum:10101001},
{name:"abc",phonenum:0101001}
]
您不必初始化 let contactsArr = [{}];它会重置你的 reducer 中的存储值。只需使用联系人存储变量
const addContact = (contacts = [], action) => {
// if (action.type = "ADD_CONTACT") {
if (action.type === "ADD_CONTACT") {
return [...contacts, action.payload];
}
return contacts;
};
//我需要使用 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}
}
//分派两个动作后我想要的最终数组是
//联系方式
[
{name:"xyz",phonenum:10101001},
{name:"abc",phonenum:0101001}
]
您不必初始化 let contactsArr = [{}];它会重置你的 reducer 中的存储值。只需使用联系人存储变量
const addContact = (contacts = [], action) => {
// if (action.type = "ADD_CONTACT") {
if (action.type === "ADD_CONTACT") {
return [...contacts, action.payload];
}
return contacts;
};