在 Google 的回调函数中访问道具时遇到问题 使用 react-google-login 登录
Trouble accessing props in callback function of Google Login using react-google-login
我正在以类似的方式使用 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,它工作正常 - 但是,loginGoogle()
函数中的 console.log(this)
打印 'undefined' 而它打印 Javascript 对象在我类似的 loginFacebook()
方法中表示整个 Login
组件。关于如何在 loginGoogle()
中访问 this.props 有什么想法吗?
在我的登录组件中:
//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);
我从这个 class 中删除了很多内容以使其更具可读性 - 如果我以任何方式包含更多代码是否有帮助,请告诉我。
尝试将 loginGoogle
定义更改为箭头函数:
loginGoogle(response) {
=> loginGoogle = (response) => {
或者绑定loginGoogle
方法,参考这个答案:
我正在以类似的方式使用 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,它工作正常 - 但是,loginGoogle()
函数中的 console.log(this)
打印 'undefined' 而它打印 Javascript 对象在我类似的 loginFacebook()
方法中表示整个 Login
组件。关于如何在 loginGoogle()
中访问 this.props 有什么想法吗?
在我的登录组件中:
//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);
我从这个 class 中删除了很多内容以使其更具可读性 - 如果我以任何方式包含更多代码是否有帮助,请告诉我。
尝试将 loginGoogle
定义更改为箭头函数:
loginGoogle(response) {
=> loginGoogle = (response) => {
或者绑定loginGoogle
方法,参考这个答案: