ComponentDidMount反应本机状态

时间:2018-10-23 13:02:52

标签: javascript reactjs react-native

我的代码:

   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执行我的功能

3 个答案:

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