【问题标题】:fetch() in js - adding new object to json serverjs 中的 fetch() - 将新对象添加到 json 服务器
【发布时间】:2020-04-23 20:10:54
【问题描述】:

我有一个关于向 json 服务器添加新对象的问题:

我有一个日历,每次更改日期后,我都想在服务器上添加这个日期。现在它看起来像这样:

[
    {
        "name": "three",
        "dates": {
            "6.01.2020": []
        },
        "id": 3
    },
    {
        "name": "four",
        "dates": {
            "5.01.2020": []
        },
        "id": 4
    }
]

和代码:

  const { day, changeDay, userObject, newDay, addNewDay, tasks } = useContext(
    UserContext
  );

  const [date, setDate] = useState(new Date());
  const onChange = date => {
    setDate(date);
    // changeDay(date.toLocaleDateString());
    addNewDay(date.toLocaleDateString());

    try {
      fetch(`http://localhost:3003/users/${userObject.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ dates: { [newDay]: [] } }),
        headers: {
          'Content-Type': 'application/json'
        }
      });
    } catch (err) {
      console.error(err);
    }
  };

一开始,我从上下文中获得了当前日期。但是在每天更改之后, newDay 正在替换一天,我希望添加它,例如:

"dates": {
"6.01.2020": [],
"7.01.2020": [],
"8.01.2020": [],
}

有人吗?

【问题讨论】:

    标签: javascript reactjs fetch react-hooks patch


    【解决方案1】:

    解决方案(必须创建新对象,映射 newDay 数组并填充对象)

    const { day, userObject, newDay, addNewDay, tasks } = useContext(UserContext);
    
      // object with today date and tasks
      let obj = { dates: [{ [day]: tasks }] };
    
      const [date, setDate] = useState(new Date());
      const onChange = date => {
        setDate(date);
        addNewDay([...newDay, date.toLocaleDateString()]);
    
        // Add new days to the object
        newDay.map((el, i) => {
          obj.dates.push({ [newDay[i]]: [] });
        });
    
        try {
          fetch(`http://localhost:3003/users/${userObject.id}`, {
            method: 'PATCH',
            body: JSON.stringify({ dates: obj.dates }),
            headers: {
              'Content-Type': 'application/json'
            }
          });
        } catch (err) {
          console.error(err);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-27
      • 2015-11-11
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 2021-12-26
      相关资源
      最近更新 更多