javascript - React-Native/Redux - 如何使用 Fetch/POST 将对象添加到现有 JSON 对象的属性?
问题描述
所以我正在构建一个 React-Native 应用程序,并使用 JSON 服务器作为我的数据库。我的 JSON 数据库文件有一个包含对象数组的对象。在每个对象中,我都有一个属性,它的值是另一个对象数组。将新对象添加到主数组中没有问题,但是,我需要将新对象添加到主对象的对象数组中。
澄清一下,我想在“items”属性中添加一个新对象。
我的 JSON 文件如下所示:
"database": [
{
"incident": "42069",
"location": "1234 ABC RD",
"date": "Wed Jun 09 2021 16:22:00 GMT-0500 (CDT)",
"items": [],
"id": 0
},
{
"incident": "69420",
"location": "1234 ABC RD",
"date": "Wed Jun 09 2021 16:22:00 GMT-0500 (CDT)",
"items": [
{
name: "ABC",
type: "DEF"
},
{
name: "GHI",
type: "JKL"
}
],
"id": 1
},
]
我的 redux 动作创建者目前看起来像这样:
传递了incidentId 参数,因此我可以访问要添加到的对象。我认为将其传递到 fetch url 仅适用于“PUT”方法,对吗?我的 baseUrl 是我的本地 JSON 服务器 url。
export const addItem = (incidentId, itemName, itemType) => dispatch => {
const newItem = {
itemName,
itemType
};
return fetch(baseUrl + 'database/' + incidentId, {
method: "POST",
body: JSON.stringify(newItem),
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
if (response.ok){
return response;
}else{
const error = new Error(`Error ${response.status}: ${response.statusText}`);
error.response = response;
throw error;
}
},
error => { throw error; }
)
.then(response => response.json())
.then(response => dispatch(fetchIncidents()))
.catch(error => {
alert('Your item could not be added\nError: ' + error.message);
});
};
显然这对我不起作用。我将如何在对象属性中发布这个新对象?
谢谢!
解决方案
推荐阅读
- azure - Azure API 首选:return=minimal header
- moodle - Moodle消息不能发送“<”符号?
- javascript - 这是对 requestAnimationFrame 的正确使用吗?
- javascript - Panzoom 库并用居中的图像填充 div
- authentication - API 身份验证最佳实践
- javascript - 没有从控制器传递到 vue 组件的道具 - vue2 和惯性.js
- asp.net-core - 除了在信号 R 服务器中响应客户端之外,我如何执行一些命令操作?
- c++ - 在 Dll 中编写静态值返回方法?
- ruby-on-rails - 尝试在 WSL1 上使用 Rails 运行带有 SSL 的 Puma 服务器
- tableau-api - 为什么总忽略过滤器?