我的代码:
componentDidMount() {
this.getEmail;
console.log("checkpoint")
}
getEmail = () => {
var email="something";
this.setState({
email: email,
});
console.log(this.state.email)
}
render() {
return (
<View>
<Text style={styles.text} onPress={this.getEmail}>email :{this.state.email}</Text>
</View>
);
}
Console.logs:
//nothing happened?
checkpoint
(onPress Text into JSX)
this.state.email
something
所以我的功能运行良好,但是ComponentDidMount不执行getEmail,但是如果我按“ email:”,这将加载我的状态,一切都很好。
我希望ComponentDidMount执行我的功能
答案 0 :(得分:1)
componentDidMount() {
this.getEmail();
console.log("checkpoint")
}
当然,在您按下文本时会执行onPress={this.getEmail}
,但这是因为onPress事件监听器将this.getEmail
变成了this.getEmail()
答案 1 :(得分:1)
您需要更改componentDidMount函数:
componentDidMount() {
this.getEmail();
console.log("checkpoint")
}
告诉我这是否是您想要的...
答案 2 :(得分:0)
您需要调用getEmail
:
componentDidMount() {
this.getEmail(); // () is added here
console.log("checkpoint")
}
您还写道:
getEmail = () => {
var email="something";
this.setState({
email: email,
});
console.log(this.state.email)
}
这是错误的。 setState
是异步,并且您登录时this.state.email
可能不存在(请查看When to use React setState callback)。要解决此问题,您应该写:
getEmail = () => {
var email="something";
this.setState({
email: email,
}, () => console.log(this.state.email));
}