//我需要使用通讯录的reducer将对象添加到数组中
// reducer
const addContact = (contacts = [], action) => {
let contactsArr = [{}];
if (action.type = "ADD_CONTACT") {
return [...contactsArr, action.payload];
}
return contacts;
};
Action
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}
}
//分派(dispatch)两个 Action 后,我想要的最终数组是
//contactsArr
[
{name:"xyz",phonenum:10101001},
{name:"abc",phonenum:0101001}
]
最佳答案
你不需要太多的 init let contactArr = [{}];它将重置您的 reducer 中的存储值。只需使用联系人存储变量
const addContact = (contacts = [], action) => {
// if (action.type = "ADD_CONTACT") {
if (action.type === "ADD_CONTACT") {
return [...contacts, action.payload];
}
return contacts;
};
关于javascript - 如何使用reducer将对象添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55693501/