需要帮助发送正确的有效负载以更新状态



我正在使用MongoDB Stitch应用程序创建一个电话簿应用程序。当我更新用户时,信息会正确保存在数据库中,但直到刷新页面后才会显示在客户端上。我相信问题出在我的reducer中,该reducer使用action.p有效负载_id,但我真的不确定是否是这样。还原剂


case 'updateContact':
return {
...state,
contacts: state.contacts.map((contact) =>
contact._id === action.payload._id? action.payload : contact
),
loading: false,
};```
Action
```const updateContact = async (contactId, contact) => {
const query = { _id: contactId };
const update = {
$set: {
contact,
},
};
const options = { upsert: false };
await items.updateOne(query, update, options);
dispatch({
type: 'updateContact',
payload: [contact, contactId],
});
};

我的数据是这样存储的:


contacts: [
{
"_id":"5eb0c9238016c9de09f3d307",
"contact":{
"name":"Anne Bonny",
"email":"anne@bonny.com",
"phone":"3213231423"
},
"owner_id":"5ea89a7e94861451f4c4fe6f"
},
{
"_id":"5eb0c93f8016c9de09f3d308",
"contact":{
"name":"Woodes Rogers",
"email":"woodes@rogers.com",
"phone":"3217037475"
},
"owner_id":"5ea89a7e94861451f4c4fe6f"
},
{
"contact":{
"name":"john silver",
"email":"longjohn@silver.com",
"phone":"9391032314"
},
"owner_id":"5ea89a7e94861451f4c4fe6f",
"_id":"5eb19220a6949dfb5c76e30b"
},
{
"contact":{
"name":"Charles Vane",
"email":"charles@vane.com",
"phone":"3921303921"
},
"owner_id":"5ea89a7e94861451f4c4fe6f",
"_id":"5eb19234a6949dfb5c76e30c"
}
]```

您已经将有效载荷作为带有contactIdcontact的数组发送到reducer,您希望有效载荷在reducer中具有_id字段。您可能只需要发送联系人并使用其中的_id字段,假设发送来更新联系人的联系人的格式为

{
"_id":"5eb0c93f8016c9de09f3d308",
"contact":{
"name":"Woodes Rogers",
"email":"woodes@rogers.com",
"phone":"3217037475"
},
"owner_id":"5ea89a7e94861451f4c4fe6f"
},

将您的操作更改为以下代码以使其工作

const updateContact = async (contactId, contact) => {
const query = { _id: contactId };
const update = {
$set: {
contact,
},
};
const options = { upsert: false };
await items.updateOne(query, update, options);
dispatch({
type: 'updateContact',
payload: contact,
});
};

如果您的联系对象只是以下格式的

{
"name":"Woodes Rogers",
"email":"woodes@rogers.com",
"phone":"3217037475"
},

你需要单独传递contactId,并像下面的一样更新你的reducer

const updateContact = async (contactId, contact) => {
const query = { _id: contactId };
const update = {
$set: {
contact,
},
};
const options = { upsert: false };
await items.updateOne(query, update, options);
dispatch({
type: 'updateContact',
payload: { contact, contactId },
});
};

减速器将如下

case 'updateContact':
return {
...state,
contacts: state.contacts.map((contact) =>
contact._id === action.payload.contactId ? { ...contact, contact: action.payload.contact } : contact
),
loading: false,
};

相关内容

最新更新