gpt4 book ai didi

javascript - 如何使用reducer将对象添加到数组中

转载 作者:行者123 更新时间:2023-12-02 23:49:57 24 4
gpt4 key购买 nike

//我需要使用通讯录的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com