ComponentDidMount 反应本机状态



我的代码:

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>
);
}

控制台日志 :

//nothing happened?
checkpoint
(onPress Text into JSX)
this.state.email
something

所以我的函数运行良好,但 ComponentDidMount 不执行 getEmail,但是如果我按"电子邮件:",这会加载我的状态,一切都很好。

我希望组件安装执行我的函数

componentDidMount() {
this.getEmail();
console.log("checkpoint")
}

当然,onPress={this.getEmail}是在按下文本时执行的,但那是因为 onPress 事件侦听器会this.getEmail变成this.getEmail()

你需要更改 componentDidMount 函数:

componentDidMount() {
this.getEmail();
console.log("checkpoint")
}

告诉我这是否是你要找的...

你需要调用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可能不存在(看看什么时候使用 React setState 回调(。要解决此问题,您应该编写:

getEmail = () => {
var email="something";
this.setState({
email: email,
}, () => console.log(this.state.email));
}

最新更新