programing

비동기 함수를 onClick in 버튼 응답으로 호출할 수 있습니까?

bestprogram 2023. 2. 26. 16:23

비동기 함수를 onClick in 버튼 응답으로 호출할 수 있습니까?

에서 비동기 함수를 호출합니다.onclick버튼을 클릭합니다.하지만 그것은 효과가 없다.inside 버튼의 비동기 기능을 onlick으로 호출할 수 있습니까?

여기 암호가 있습니다.

[ Filter ]단추

const FilterButton = (props) => {

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

fetch Invoices 비동기 함수

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

컴포넌트에 함수를 전달하기 위한 코드

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

이것은, 비동기라고 하는 것입니다.onClick:

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

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

비동기 기능:

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

    let result = await promise

    alert(result);
}

버튼 컴포넌트 호출:

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

대신, 해 보세요.

<button className="btn btn-secondary" onClick={this.handleFetchInvoices}>Filter</button>
handleFetchInvoices(){
this.props.fetchInvoices
}
<button 
  onClick={(e) => (async () => {
    try {
      const invoices = await getInvoices(this.currentState.params);
    } catch () {

    }
  })()} 
>I am a button!</button>

일반적으로 버튼을 클릭할 때마다 버튼 내부에 2배 기능을 만드는 것은 좋지 않습니다.하지만 그것은 효과가 있다.

언급URL : https://stackoverflow.com/questions/54779318/can-async-functions-be-called-in-onclick-in-button-react