react-native初始生命周期钩子没有被调用

时间:2017-03-24 22:13:00

标签: reactjs react-native

使用下面的代码,我无法在Text内部引用TestText组件,直到AFTER触发其他重新渲染。我疯了吗?或者这是反应原生的错误吗?

正如预期的那样,在启动应用程序后立即调用

constructor”,“componentWillMount”和“render”。但是,在5秒延迟后通过ref手动触发重新渲染之前,不会调用“componentDidMount”和“this.setState()”。

平台:Android

React-Native Version:0.42.3

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class TestText extends Component {

    constructor(props, context) {
        super(props, context);
        console.warn('constructor');
        this.textRef = null;
    }

    componentWillMount() {
        console.warn('willMount');
    }

    componentDidMount() {
        console.warn('didMount');
    }

    render() {
        console.warn('render');
        return (
            <View>
                <Text
                    ref={(me) => {
                        console.warn('ref: ' + (me ? 'not null' : 'null'));
                        this.textRef = me;
                    }}>
                    {'TEST'}
                </Text>
            </View>
        );
    }

}

export default class AwesomeProject extends Component {

  constructor(props, context) {
      super(props, context);
      this.state = {
        test: 0
      };
      setTimeout(() => {
        this.setState({
            test: 1
        });
      }, 5000)
  }

  render() {
    return (
      <View style={styles.container}>
        <TestText />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

0 个答案:

没有答案