[英]ComponentDidMount react native state
My code: 我的代码:
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 : Console.logs:
//nothing happened?
checkpoint
(onPress Text into JSX)
this.state.email
something
So my function works well but ComponentDidMount doesn't execute getEmail, but if i press "email :" this load my state and all is fine. 因此,我的功能运行良好,但是ComponentDidMount不执行getEmail,但是如果我按“ email:”,这将加载我的状态,一切都很好。
I would like that ComponentDidMount execute my function 我希望ComponentDidMount执行我的功能
componentDidMount() {
this.getEmail();
console.log("checkpoint")
}
Of course, onPress={this.getEmail}
is executed when you press the text, but that's because onPress event listener make this.getEmail
into this.getEmail()
当然,当您按文本时,将执行onPress={this.getEmail}
,但这是因为onPress事件侦听器将this.getEmail
放入this.getEmail()
You need to change componentDidMount function: 您需要更改componentDidMount函数:
componentDidMount() {
this.getEmail();
console.log("checkpoint")
}
and tell me if it's what you looking for... 告诉我你是否在寻找...
You need to invoke getEmail
: 您需要调用getEmail
:
componentDidMount() {
this.getEmail(); // () is added here
console.log("checkpoint")
}
Also, you wrote: 另外,您写道:
getEmail = () => {
var email="something";
this.setState({
email: email,
});
console.log(this.state.email)
}
which is wrong. 这是错误的。 setState
is asynchronous and this.state.email
might not be there when you log it (take a look on When to use React setState callback ). setState
是异步的,并且在记录它时this.state.email
可能不存在(请看何时使用React setState callback )。 To fix this you should write: 要解决这个问题,您应该写:
getEmail = () => {
var email="something";
this.setState({
email: email,
}, () => console.log(this.state.email));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.