Javascript 如何使用JSON服务器更新ReactJS中的数据

Javascript 如何使用JSON服务器更新ReactJS中的数据,javascript,json,reactjs,typescript,Javascript,Json,Reactjs,Typescript,我是新手,可以从JSON文件中获取数据。现在我需要更新这些值并提交到JSON文件。我正在努力提交JSON文件中更新的输入字段 submitEmpData(event) { event.preventDefault(); this.state.empProjects.allocation=this.state.allocation; this.setState({ empProjects:this.state.empProjects });

我是新手,可以从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);
  }

有几种方法可以在react中触发渲染:

将新值作为道具发送到子组件,或

您可以使用一种状态形式(例如挂钩或
setState
)来更新组件状态


在您的示例中,在回迁承诺被拒绝或解决后,添加一个
setState
,设置渲染所需的数据。

有一些方法可以触发react中的渲染:

将新值作为道具发送到子组件,或

您可以使用一种状态形式(例如挂钩或
setState
)来更新组件状态


在您的示例中,在fetch承诺被拒绝或解决后添加一个
setState
,设置呈现所需的数据。

以下方法更改JSON是错误的,因为
this.state
是一个对象,javascript将检查引用以进行比较()

除此之外,您可以使用创建新对象:

this.setState({
   ...this.state, this.state.empProjects: { ...this.state.empProjects, allocation: "NEW value"}
})
还要使用fetch发送请求,请执行以下操作:


以下方法更改JSON是错误的,因为
this.state
是一个对象,javascript将检查引用以进行比较()

除此之外,您可以使用创建新对象:

this.setState({
   ...this.state, this.state.empProjects: { ...this.state.empProjects, allocation: "NEW value"}
})
还要使用fetch发送请求,请执行以下操作:


为了更好地理解代码,我对代码进行了重组。我相信
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;
  }
}
请在评论中给我任何澄清


为了更好地理解代码,我对代码进行了重组。我相信
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;
  }
}
请在评论中给我任何澄清

body:JSON.stringify(this.state.empProjects)body:JSON.stringify(this.state.empProjects)