9
votes

Les fonctions asynchrones peuvent-elles être appelées dans onClick dans le bouton react

Je vais appeler la fonction asynchrone dans l'événement onclick dans le bouton. Mais ça ne fonctionne pas. Est-il possible d'appeler la fonction async à l'intérieur du bouton onlick?

Voici le code.

Bouton Filtrer

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

Fonction asynchrone fetchInvoices

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

code pour passer la fonction au composant

const FilterButton = (props) => {

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


2 commentaires

Ça va marcher. Quelle est l'erreur?


Maintenant ça marche. Cette fetchInvoice dans SeachField est passée en paramètre. J'ai ajouté fetchInvoices = {this.fetchInvoices} à la place fetchInvoices = {this.props.fetchInvoices}


3 Réponses :


-2
votes

Essayez ceci

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

au lieu de

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


0 commentaires

-1
votes

À la place, essayez de faire

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


1 commentaires

Cela ne fait rien. Ce devrait être: handleFetchInvoices () {this.props.fetchInvoices (); }



22
votes

C'est ainsi que j'appelle mes asynchrones dans un onClick :

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

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


2 commentaires

Je pense que c'est exactement la même chose que: