簡體   English   中英

在異步函數reactjs之后從另一個組件調用一個方法

[英]Call a method from another Component after the Async function reactjs

我有2個組件,第一個組件具有一個在第二個組件的async函數之后調用的函數,我想要做的是類似於vue的this.$emit()函數,該函數隨時從該組件調用偵聽器,我該如何有反應嗎?

這是我的第一個組成部分

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

這是我的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

這是您如何從父代傳遞的道具接收數據/使用方法的方法:

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

在第一個組件上,您正在向第二個組件發送道具。 這是文檔: https : //reactjs.org/docs/components-and-props.html

要訪問第二個組件中的onDataReceived ,可以編寫:

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

您的第二個組件必須調用asyncFuncion ,然后在asyncFuncion內部,您可以從props中調用callThis函數。

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

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

並且不要忘記也綁定該callThis ,或者只是使用胖箭頭功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM