首页 > 解决方案 > 如何使用 JSON 服务器更新 ReactJS 中的数据

问题描述

我是新手,我可以从 JSON 文件中获取数据。现在我需要更新这些值并提交到 JSON 文件。我正在努力在 JSON 文件中提交更新的输入字段

 submitEmpData(event) {
    event.preventDefault();
    this.state.empProjects.allocation=this.state.allocation;
      this.setState({
        empProjects:this.state.empProjects
      });
    return fetch('http://localhost:3000/Employee/' + this.state.empProjects.id, {
        method: 'PUT',
        mode: 'CORS',
        body: this.state.empProjects,
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
  }

标签: javascriptjsonreactjstypescript

解决方案


我已经重组了代码以便更好地理解。我相信JSON.stringify()并且res.json()可能需要您研究的地方。

async submitEmpData(event) {
  event.preventDefault();

  let { empProjects, allocation } = this.state;

  empProjects.allocation = allocation;

  // updating the state
  this.setState({
    empProjects,
  });

  // calling the api
  try {
    let res = await  fetch("http://localhost:3000/Employee/" + this.state.empProjects.id, {
      method: "PUT",
      mode: "CORS",
      body: JSON.stringify(this.state.empProjects),
      headers: {
        "Content-Type": "application/json"
      }
    })
    return await res.json();
  } catch (err) {
    return err;
  }
}

请在评论中对我进行任何澄清


推荐阅读