【问题标题】:Can async functions be called in onClick in button react可以在按钮反应的onClick中调用异步函数吗
【发布时间】:2021-10-05 18:18:23
【问题描述】:

我将在按钮的onclick 事件中调用异步函数。但它不起作用。是否可以在按钮 onlick 中调用异步函数?

这里是代码。

过滤按钮

const FilterButton = (props) => {

return (
    <div className="p-2 ">
        <button className="btn btn-secondary" onClick={props.fetchInvoices}>Filter</button>
    </div>
 );
};

fetchInvoices 异步函数

fetchInvoices = async () => {
    const invoices = await getInvoices(this.currentState.params);
    this.props.store.dispatch(UpdateInvoices(invoices));
};

将函数传递给组件的代码

 <SearchField store = {this.props.store} fetchInvoices={this.fetchInvoices}/>

【问题讨论】:

  • 它会起作用的。什么错误?
  • 现在它正在工作。 SeachField 中的 fetchInvoice 作为参数传递。我添加了 fetchInvoices={this.fetchInvoices} 而不是 fetchInvoices={this.props.fetchInvoices}

标签: reactjs


【解决方案1】:

这就是我在 onClick 中调用异步的方式:

<Button onClick={async () => {await this.asyncFunc("Example");} }/>

async asyncFunc(text) {
    console.log(text);
}

【讨论】:

  • 我认为这与:
  • 这没有任何帮助。异步委托在不等待其结果的情况下执行。
  • 它有助于在文档加载时不触发点击功能,仅在点击时触发
【解决方案2】:

你的async function

const asyncFunc = async () => {
    let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("I am a done promise!"), 3000)
    });

    let result = await promise

    alert(result);
}

您的button component 电话:

<button onClick={asyncFunc} >I am a button!</button>

【讨论】:

    【解决方案3】:
    <button 
      onClick={(e) => (async () => {
        try {
          const invoices = await getInvoices(this.currentState.params);
        } catch () {
    
        }
      })()} 
    >I am a button!</button>
    

    一般来说,每次点击时在按钮内创建 2x 个函数是一种不好的做法。但它有效。

    【讨论】:

      【解决方案4】:

      相反,尝试做

      <button className="btn btn-secondary" onClick={this.handleFetchInvoices}>Filter</button>
      handleFetchInvoices(){
      this.props.fetchInvoices
      }
      

      【讨论】:

      • 这没有任何作用。它应该是:handleFetchInvoices() { this.props.fetchInvoices(); }
      猜你喜欢
      • 2014-06-14
      • 2019-08-18
      • 2021-12-08
      • 2018-06-26
      • 2019-12-11
      • 1970-01-01
      • 2022-12-04
      • 2021-11-12
      • 1970-01-01
      相关资源
      最近更新 更多