无法读取未定义的属性‘props’
2016-07-15
1373
你得对我宽容点。。。对 React Native 非常陌生
我有这段代码,非常简单:
export default class signup extends Component {
constructor(props){
super(props);
this.state = {
loaded: true,
email: '',
password: ''
};
}
signup(){
this.setState({
loaded: false
});
firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function() {
this.props.navigator.push({
component: Login
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
}
goToLogin(){
this.props.navigator.push({
component: Login
});
}
render() {
return (
<View style={styles.container}>
<Header text="Signup" loaded={this.state.loaded} />
<View style={styles.body}>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
placeholder={"Email Address"}
/>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
secureTextEntry={true}
placeholder={"Password"}
/>
<Button
text="Signup"
onpress={this.signup.bind(this)}
button_styles={styles.primary_button}
button_text_styles={styles.primary_button_text} />
<Button
text="Got an Account?"
onpress={this.goToLogin.bind(this)}
button_styles={styles.transparent_button}
button_text_styles={styles.transparent_button_text} />
</View>
</View>
);
}
}
AppRegistry.registerComponent('signup', () => signup);
我不明白的是,如果我点击“转到登录”按钮,它会完美运行该功能并转到登录页面
goToLogin(){
this.props.navigator.push({
component: Login
});
}
但是当我点击注册按钮时,它会抛出错误
Cannot read property 'props' of undefined
我想我可以把同样的代码块放进去运行:
this.props.navigator.push({
component: Login
});
但是它会导致错误。我有点困惑为什么会发生这种情况,因为它在另一个函数中运行得很好。。我确信这只是我和我对 React Native 缺乏了解。。 谢谢大家!
1个回答
您需要使用绑定或箭头函数
firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function() {
this.props.navigator.push({
component: Login
});
}.bind(this), function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
OR
firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(() => {
this.props.navigator.push({
component: Login
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
Piyush.kapoor
2016-07-15