javascript - 使用 onClick HTTP 请求/输出作为警报窗口的反应按钮
问题描述
我想在单击按钮时发出 http get 请求。并且还希望查看 json 数据 / 或转换为字符串作为输出,例如在警报窗口中。
// async function
async fetchAsync () {
// await response of fetch call
let response = await fetch('https://api.0x.org/swap/v1/quote?sellToken=ETH&buyToken=DAI&sellAmount=1000000000000000000');
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return JSON.stringify(data);
}
buttonEvent(){
alert(
this.fetchAsync()
.then(data => alert(data))
.catch(reason => console.log(reason.message))
);
}
render() {
return (
<button onClick = {this.buttonEvent}>Close Position</button>
)
}
}
上面可以看到按钮组件的代码。当我单击应用程序中的按钮时,我收到错误“TypeError:无法读取未定义的属性'fetchAsync'”
如何在我的应用程序中显示来自 http 请求的值?
解决方案
fetchAsync
如果你不让它们自动绑定,你应该绑定函数。
您可以将函数绑定在constructor
这是一个例子
class Example {
constructor (props) {
super(props)
this.fetchAsync = this.fetchAsync.bind(this)
}
async fetchAsync () {
// ... do something
推荐阅读
- azure-devops - Web部署后如何排除工件文件?
- influxdb - 基于 influxdb 中其他模板变量的动态模板变量值 - chronograf
- qt - macdeployqt 不复制 QtWebView 插件
- python - 在 Ubuntu 16.04 上导入模块时出现语法错误
- reactjs - 无法安装serve来安装react PWA
- javascript - 如何随着形状的旋转和位置的变化移动点
- r - 如何将重复出现的长对数据集转换为矩阵频率表
- java - Java AWS Lambda 处理程序 - 深度嵌套的 Json
- c# - 没有常量类型参数的理论测试迭代不会在测试资源管理器中显示为单独的迭代
- docker - 私有注册表的 Docker 拉取限制