简体   繁体   中英

Call a method from another Component after the Async function reactjs

I have 2 components, the first component has a function that calls after the async function of the second component, what I want to do is something like vue's this.$emit() function that calls a listener from that component anytime, how can I do that in react?

This is my first component

import React, { Component } from 'react';
import SecondComponent from '../Path/to/second/component'

class MainMenu extends Component {
    callThis (data) {
        console.log(data)
    }

    render () {
        return <SecondComponent onDataReceived = {this.callThis} />
    }
}

export default FirstComponent

And this is my SecondComponent

import React, { Component } from 'react';

class SecondComponent extends Component {
    async asyncFunction () {
        const data = await getDataFromApi()
        // call the function from first component here...
    }

    render () {
        return <button onClick={() => this.asyncFuncion} />
    }
}

export default FirstComponent

this is how you can receive data/use methods from parent passed props:

async asyncFunction () {
    const data = await getDataFromApi()
    // call the function from first component here...
    this.props.onDataReceived(data);
}

On your first component, you are sending a props to your second components. Here is the documentation : https://reactjs.org/docs/components-and-props.html

To access onDataReceived in your second component you could write :

async asyncFunction () {
        const data = await getDataFromApi()
        this.props.onDataReceived(data);
    }

Your second component must invoke asyncFuncion , and then inside asyncFuncion you can call the callThis function from the props

class SecondComponent extends Component {
    async asyncFunction () {
        const data = await getDataFromApi()
        this.props.onDataReceived(data)
    }

    render () {
        return <button onClick={() => this.asyncFuncion()} />
    }
}

and do not forget to bind that callThis as well, or just use fat arrow function:

class MainMenu extends Component {
    callThis = (data) => {
        console.log(data)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM