I have made this class:
import React, {Component} from 'react';
import {
View,
ActivityIndicator,
Button
} from 'react-native';
import Auth from '../api/Auth';
export default class LoginScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
alreadyLoggedIn: true
};
this.redirectToHome.bind(this);
this.loginWithFacebook.bind(this);
}
componentWillMount() {
Auth.isAlreadyLoggedIn().then((res) => {
if(res == true) {
this.redirectToHome();
} else {
this.setState({alreadyLoggedIn: false});
}
});
}
redirectToHome() {
this.props.navigator.resetTo({
screen: 'homeScreen',
title: 'Meetups'
});
}
loginWithFacebook() {
Auth.loginWithFacebook().then((success) => {
if(success == true) {
this.redirectToHome();
}
}).catch((err) => {
console.error(err);
});
}
render() {
return(
<View>
{this.state.alreadyLoggedIn == false &&
<Button title="Login with Facebook" onPress={this.loginWithFacebook} />
}
{this.state.alreadyLoggedIn == true &&
<ActivityIndicator animating={this.state.alreadyLoggedIn} />
}
</View>
);
}
}
Inside the loginWithFacebook
function, when it reaches the line where it calls the redirectToHome
function, it says this:
_this3.redirectToHome is not a function
Am I accessing this function in a wrong manner? I can’t make the function static and it required the this
object.
What should I do?
2
Answers
You need to actually update the ‘member functions’ in the constructor:
The problem is that you have done the binding for the functions incorrectly in the constructor.
this.loginWithFacebook.bind(this);
will return a new function after proper binding and you then need to use the function returned. Now since you did not assign this newly added function, withthis.loginWithFacebook
you will be refererring to your own defined function without the binding and hencethis.redirectToHome
won’t work sincethis
inside it wont refer to the correct context