【问题标题】:Call a method from another Component after the Async function reactjs在异步函数 reactjs 之后从另一个 Component 调用方法
【发布时间】:2019-08-26 10:38:48
【问题描述】:

我有 2 个组件,第一个组件有一个在第二个组件的异步函数之后调用的函数,我想做的是类似于 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

这是我的第二个组件

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

【问题讨论】:

  • 第二个组件的 onClick 没有执行 asyncFunction;要么写 onClick={this.asyncFunction} 要么 onClick={()=>this.asyncFunction()} 在你的 asyncFunction 里面调用 this.props.onDataReceived( );

标签: javascript reactjs function asynchronous


【解决方案1】:

你的第二个组件必须调用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)
    }

【讨论】:

    【解决方案2】:

    在您的第一个组件上,您正在向第二个组件发送一个道具。 这是文档:https://reactjs.org/docs/components-and-props.html

    要在您的第二个组件中访问onDataReceived,您可以编写:

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

    【讨论】:

      【解决方案3】:

      这是您可以从父传递的道具接收数据/使用方法的方式:

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

      【讨论】:

        猜你喜欢
        • 2014-09-13
        • 1970-01-01
        • 2020-03-04
        • 1970-01-01
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        相关资源
        最近更新 更多