javascript - 如何使用 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);
}
解决方案
我已经重组了代码以便更好地理解。我相信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;
}
}
请在评论中对我进行任何澄清
推荐阅读
- python - pandas 按多列分组并根据多个条件删除行
- getstream-io - Getstream-如何过滤假喜欢?
- generics - Dart:如何将泛型方法绑定到嵌套的泛型参数?
- excel - 公式中使用的值的数据类型错误”错误 - vba
- javascript - 同一域内不同应用程序的 Cookie Session 替代方案
- html - 有没有办法通过python获取动态html
- javascript - 如何避免在渲染方法中使用 setState?
- ansible - 没有从清单文件中挑选主机
- html - 在设置为对齐的嵌套 div 中水平居中文本
- c# - 如果用户没有权限,如何在登录后从菜单中隐藏 Web 表单?