【发布时间】:2020-11-25 14:02:30
【问题描述】:
我正在尝试在我的班级中实现 Facebook 登录。我创建了一个按钮组件,但是当我调用 Facebook api 并尝试调度一个注册函数时,我得到了未定义的道具。 这是我的组件:
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { LoginManager, AccessToken, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {register} from '../Actions/authActions';
class Login extends Component {
constructor(props) {
super(props);
}
_fbAuth = () => {
LoginManager.logInWithPermissions(['public_profile','email']).then(function(result){
if(result.isCancelled){
console.log('loging cancelled')
}
else {
AccessToken.getCurrentAccessToken().then((data) => {
let accessToken = data.accessToken;
let facebookId = data.userID;
const responseInfoCallback = (error, result) => {
if (error) {
alert('Error logging in with Facebook');
}
else {
console.log('Props here are empty', this.props);
this.props.registerSubmit({
"customerName": result.name,
"customerTel": '000000000',
"customerEmail": result.email,
"customerPassword": facebookId
}).then(response => {
console.log('RESPONSE', response);
if (response && response.Success) {
this.props.navigation.navigate('App');
AsyncStorage.setItem('customerEmail', data.email);
AsyncStorage.setItem('customerPassword', data.password);
} else {
this.props.navigation.navigate('Auth');
}
});
}
}
const infoRequest = new GraphRequest('/me', {
accessToken: accessToken,
parameters: {
fields: {
string: 'name,picture,email'
}}
}, responseInfoCallback);
new GraphRequestManager().addRequest(infoRequest).start();
});
}}, function (error) {
console.log('Error logging with facebook');
});
}
render() {
return (
<View style={styles.container}>
<Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this._fbAuth.bind(this)} style={styles.signInButton}>
Facebook login
</Icon.Button>
</View>
)
}
};
const mapDispatchToProps = (dispatch) => {
// Action
return {
// Login
registerSubmit: (data) => dispatch(register(data)),
};
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
signInButton: {
width: 358,
height: 48
}
});
export default connect(null, mapDispatchToProps)(Login);
当我进入回调函数时,this.props 是空的,因此 registerSubmit 是未定义的。这是我第一个使用类组件的项目,我通常使用钩子。我做错了什么?
【问题讨论】:
-
在Asyncstorage.setItem之后返回响应
-
因为
this不再引用Login,所以它有不同的上下文。您需要绑定函数或将 this 作为全局变量引用(例如 _this = this),或者只使用箭头函数(未定义自己的 this)
标签: react-native react-redux fbsdk