首页 > 解决方案 > 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);
    });
};

显然这对我不起作用。我将如何在对象属性中发布这个新对象?

谢谢!

标签: javascriptreactjsreact-nativereduxredux-thunk

解决方案


推荐阅读