使用react-google-login无法访问Google Login的回调函数中的道具 [英] Trouble accessing props in callback function of Google Login using react-google-login
问题描述
我在我的React-中使用 react-google-login redux项目,并且无法访问存在该登录按钮的组件的道具.我以类似的方式使用了 react-facebook-login ,它可以正常工作-但是, loginGoogle()
函数中的 console.log(this)
打印'undefined',而打印表示整个 Login
组件的Javascript对象在我类似的 loginFacebook()
方法中.关于如何在 loginGoogle()
中访问this.props的任何想法?
I'm using react-google-login in my react-redux project and having trouble accessing the props for the component in which this login button exists. I used react-facebook-login in a similar way and it works fine - however, console.log(this)
in the loginGoogle()
function prints 'undefined' whereas it printed the Javascript object representing the whole Login
component in my similar loginFacebook()
method. Any ideas as to how I can access this.props in loginGoogle()
?
在我的登录组件中:
//all needed import statements
class Login extends Component {
loginGoogle(response) {
console.log(response);
this.props.loginGoogleRequest(response.profileObj.email, response.accessToken, response.tokenObj.expires_in)
}
render() {
<GoogleLogin
clientId="{client id here}"
onSuccess={this.loginGoogle}
className="custom-google-btn"
/>
}
function mapDispatchToProps(dispatch) {
return {
loginGoogleRequest: (email, accessToken, expiresIn) => {
//some code that isn't being reached
}
}
}
export default connect(mapDispatchToProps)(Login);
为了使该类更具可读性,我从该类中减少了很多内容-请让我知道如果我以任何方式包含更多代码是否有帮助.
I trimmed a lot of the fat out of this class in order to make it more readable - please let me know if it would help if I included more code in any way.
推荐答案
尝试将 loginGoogle
定义更改为Arrow函数: loginGoogle(response){
=> loginGoogle =(response)=>{
Try change loginGoogle
definition to Arrow function:
loginGoogle(response) {
=> loginGoogle = (response) => {
箭头函数不会创建自己的箭头this",则使用封闭执行上下文的this值.
或者您可以绑定 loginGoogle
方法,请参考以下答案:为什么JSX道具不应该使用箭头功能
Or you may bind loginGoogle
method, refer to this answer:
Why JSX props should not use arrow functions
这篇关于使用react-google-login无法访问Google Login的回调函数中的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!