可以在onClick in按钮中调用异步功能吗

时间:2019-02-20 05:20:15

标签: reactjs

我将在按钮的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}/>

4 个答案:

答案 0 :(得分:1)

您的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>

答案 1 :(得分:0)

尝试一下

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

代替

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

答案 2 :(得分:0)

相反,请尝试

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

答案 3 :(得分:0)

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

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

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