如何使用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);
}

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

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

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

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

为了更好地理解,我重新构造了代码。我相信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是错误的,因为this.state是一个对象,javascript将检查引用以进行比较(请参阅此(。

this.state.empProjects.allocation=this.state.allocation;
this.setState({
empProjects:this.state.empProjects
});

您可以使用排列运算符创建一个新对象:

this.setState({
...this.state, this.state.empProjects: { ...this.state.empProjects, allocation: "NEW value"}
})

同样要使用fetch发送请求,正文必须与内容类型匹配:

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

最新更新