React Native - Facebook登录无法设置状态
问题描述:
我已经在我的项目中完成了Facebook登录功能,但是当登录成功时,我不能登录setState
。我得到这个错误this.setState is not a function
。我试图创建一个单独的函数调用成功后,setState
,结果是一样的,告诉我我的功能不是一个函数。我该怎么办 ?React Native - Facebook登录无法设置状态
constructor(props) {
super(props);
this.state = {
fblogindone:false,
};
}
_fbAuth(){
// Attempt a login using the Facebook login dialog asking for default permissions and email.
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
function(result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
// Create response callback.
const responseInfoCallback = function(error, result) {
if (error) {
console.log(error);
alert('Error fetching data: ' + error.toString());
} else {
console.log(JSON.stringify(result));
this.setState({
fblogindone:true
});
}
}
// Create a graph request asking for user email and names with a callback to handle the response.
const infoRequest = new GraphRequest('/me',{
parameters: {
fields: {
string: 'id,name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
},
function(error) {
alert('Login fail with error: ' + error);
}
);
}
render() {
return(
<View style={styles.topcontainer}>
<TouchableOpacity activeOpacity={0.9} onPress={()=> this._fbAuth()}>
<FoIcon name="user-circle-o" size={33} color="#fff"/>
</TouchableOpacity>
</View>
);
}
答
您必须通过箭头函数或直接绑定将您的(this)上下文绑定到该函数。所以你会改变你的函数的声明。
_fbAuth(){
到
_fbAuth =() => {
OR你会在你的构造函数中添加。
constructor(props) {
super(props);
this.state = {
fblogindone:false,
};
this._fbAuth = this._fbAuth.bind(this)
}
答
我修复了我自己的错误,所以我发布我的解决方案,希望以后可以帮助其他人。首先,我把函数名改为_fbAuth =() =>{
,然后里面的子函数返回所有改为箭头函数,(result) => {
和responseInfoCallback = (error, result) =>{
,然后this
可以在我的facebook登录回调里面使用。
_fbAuth =() =>{
// Attempt a login using the Facebook login dialog asking for default permissions and email.
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
(result) => {
if (result.isCancelled) {
alert('Login cancelled');
} else {
// Create response callback.
const responseInfoCallback = (error, result) =>{
if (error) {
console.log(error);
alert('Error fetching data: ' + error.toString());
} else {
this.setState({
fblogindone:true
});
}
}
// Create a graph request asking for user email and names with a callback to handle the response.
const infoRequest = new GraphRequest('/me',{
parameters: {
fields: {
string: 'id,name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
},
function(error) {
alert('Login fail with error: ' + error);
}
);
}
同时使用'_fbAuth =()=> {'和'this._fbAuth = this._fbAuth.bind(这)'也有同样的结果'this.setState不是function' –
我回答我自己的问题 –