[英]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.