我有一个需要调用函数的组件,并以某种方式将结果传递给return()
方法。
组件:
checkUserRole = () => {
//do stuff
//return OBJECT
}
render() {
var {OBJECT} = this.checkUserRole() // this is my attempt but getting checkUserRole is undefined
return (
<AuthUserContext.Consumer>
{authUser =>
condition(OBJECT) // the OBJECT needs to go here
? <Component {...this.props} user={authUser}/>
: null
}
</AuthUserContext.Consumer>
)
}
如何正确调用函数并将对象传递给三元表达式?
编辑
checkUserRole = () => {
this.props.firebase.auth.onAuthStateChanged(
authUser => {
authUser.getIdTokenResult()
.then((result) => {
return result
})
}
)
}
答案 0 :(得分:0)
应该能够使checkUserRole异步,然后等待结果。
async checkUserRole = () => { // Declare as async
this.props.firebase.auth.onAuthStateChanged(
authUser => {
authUser.getIdTokenResult()
.then((result) => {
return await result // Utilize await for sync flow.
})
}
)
}
您应该从componentDidMount而不是render调用它。然后将结果传递到您的状态,以便稍后渲染。