reactjs - 在 reactjs 中调用
问题描述
这是我的服务方法,我需要通过传递一个 id 对 API 进行 put 调用。这是正确的方法吗,因为我无法访问我的 .put URL
ENDPOINTS = {
SAMPLE: "/sample",
};
这是我的服务方法:
updateApi(): Promise<any> {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
// data
};
const id = sample.id;
return http
.put(`${this.ENDPOINTS.SAMPLE}${id}`, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
解决方案
不确定你是否有任何理由在http
这里使用,但如果你很灵活,那么试试fetch
react 中可用的 API。
const requestOptions = {
method: 'PUT',
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
body: data
};
fetch(`${ENDPOINTS.SAMPLE}/${sample.id}`, requestOptions)
.then(response => response.json())
.then(data => this.setState({ // update data here }));
如果您在组件中直接调用 API,则可以将上述代码放在componentDidMount
.
如果您遇到任何问题,请告诉我!
推荐阅读
- bash - 命令查找字符串并替换另一个字符串 PROBLEM 2 (txt 格式)
- sas - SAS v9.4M4 存储过程 Web 应用程序显示额外的空白
- python - 切片后根据条件删除熊猫数据框中的行
- database - 如何使用 Thymeleaf 从数据库(oracle)显示我的图像?
- android - 将 SwipeRefreshLayout 微调器定位到低于容器的位置
- mysql - Mysql关于具有多个键的重复键更新(一个主键和一个具有多列的唯一键) Dapper
- swift - 为弯曲物体定义物理体
- arrays - 纸牌游戏 - 我怎么能做出这样的声明?
- javascript - 使用 react-countdown-circle-timer 仅显示几分钟的反应
- javascript - 使用 Stryker 进行突变测试时出现无意义的突变