首页 > 解决方案 > 使用 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 请求的值?

标签: javascriptreactjs

解决方案


fetchAsync如果你不让它们自动绑定,你应该绑定函数。

您可以将函数绑定在constructor

这是一个例子

class Example {
  constructor (props) {
    super(props)
    this.fetchAsync = this.fetchAsync.bind(this)
  }

  async fetchAsync () {
    // ... do something

推荐阅读