使用react-native在propsDidMount中使用props数据

时间:2016-02-24 12:52:38

标签: reactjs react-native

关于这一次,我一直在努力工作24小时。 问题是,我在父类中传递道具并在我的子组件中调用道具数据。当我签入渲染方法时,数据显示正确,但在componentDidMount中调用时,它显示为null。

以下是我的代码示例

class parent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      isOpen: false,
      day:'monday',
      data:[],
      data1:[]
    }
  }

  back () {
    this.props.navigator.pop();
  }

  Mon(){
    var record=[];
    this.state.data.map((data) => {
      if(data.frequency[0].day == 'Monday'){
        record.push(data);
      }
    });
    this.setState({data1:record});
  }

  componentWillMount() {
    this.fetchData();
  }

  fetchData() {
  //here i am getting the data from service and set the data to the state
  }

  render(){
    return(
      <View style={styles.Maincontainer}>
        <View style={styles.navbar}>
          <View style={styles.navbarContainer}>
            <View style={styles.navbarIcon}>
              <TouchableOpacity style={styles.button} onPress={() => this.back()}>
                <Image
                  style={styles.menu2}
                  source={require('image!nav_arrow')} />
                <Text style={styles.navbuttonText}>Back</Text>
              </TouchableOpacity>
            </View>
            <View style={styles.navbarText}>
              <Text style={styles.title}>Title</Text>
            </View>
            <View style={styles.navbarButton}>
            </View>
          </View>
        </View>
        <View style={styles.subMainContainer}>
          <View style={styles.weekHeader}>
            <View style={styles.weekRow}>
              <Text style={styles.text} onPress={this.Mon.bind(this)}>Mon</Text>
            </View>
          </View>
          <View style={styles.listBody}>
            {this.state.data1.length == 0 ?(
              <List data={this.state.data} />
            ) : (
              <List data={this.state.data1}/>
            )}
          </View>
        </View>
      </View>
    );
  }
}

在我的子组件中,我想在ListView中显示取自父组件的数据

class List extends React.Component{
   constructor(props){
    super(props);
    this.state = {
       dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
       }),
       isLoading: true
    };
  }
 componentDidMount(){ //**here props data shows empty**
    alert("didMount:"+JSON.stringify(this.props.data));
    var data=this.props.data
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data),
      isLoading: false
    });
  }
  render() { //**In this alert it shows correct data**
    alert("data:"+JSON.stringify(this.props.data));
   if (this.state.isLoading) {
      return this.renderLoadingView();
    }
    return(
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderSchedule.bind(this)}
        automaticallyAdjustContentInsets={false}/>
      );
  }
  renderLoadingView(){
    return(
       <View style={styles.loading}>
       <ActivityIndicatorIOS
                size='large'/>
        <Text>
          Loading Schedule...
        </Text>
      </View>
      );
  }
  renderSchedule(data){
    return(
      <View style={styles.ListContainer}>
          <View style={styles.subContainer}>
            <Text style={styles.classText}>Class Name: {data.name}</Text>
             {data.frequency[0].day == null ? (
              <Text style={styles.Day}>Day: {data.frequency[0].date}</Text>
              ):
            <Text style={styles.Day}>Day: {data.frequency[0].day}</Text>
          }
          </View>
          <View style={styles.subContainer1}>
            <Text style={styles.startTime}>Start: {data.frequency[0].from}</Text>
            <Text style={styles.endTime}>End: {data.frequency[0].to}</Text>
          </View>
      </View>
      )
  }
}

这里我想要的是,最初我需要显示总数据,当点击文本父类时需要更改数据。我想在ListView中显示数据。我已经在上面解释了我的问题,所以可以任何人给我建议如何解决我的问题,任何帮助非常感谢

2 个答案:

答案 0 :(得分:3)

我的猜测是componentDidMount()中的警报是空的,因为它只在数据仍然为空时调用一次,而在每次更改状态或道具时调用render()。 / p>

我希望警报流看起来像这样:

  • 从孩子的渲染调用警报:“data:(empty)”
  • 从孩子的didMount调用警报:“didMount :( empty)”
  • 用户点击父级内容,状态更改,重新呈现触发
  • 来自儿童渲染的警报:“数据:FOO-content”

React不会在第二次通过时调用componentDidMount()。如果您希望在子项的每次更新时填充数据源,则需要向您的孩子添加componentDidUpdate()方法,并附上componentDidMount()内的代码副本。

总的来说:我建议你阅读React's explanation of component lifecycle and methods。我有一种感觉,你在componentDidMount()内做的准备可能更好地放在其他地方:

  • 创建一个DataSource并使用props中的数据进行初始填充:getInitialState()
  • 使用新道具中的数据更新数据源:componentWillReceiveProps()

答案 1 :(得分:0)

我在React中发现,如果我想基于this.props来准备组件的初始状态,则应该在componentDidUpdate中而不是componentDidMount中进行。组件不会使用父组件中的填充道具进行安装,而只能使用它们进行更新

在执行正常的React并在子组件的console.log(this.props)方法中执行render时,我注意到了这一点。它最初会以空记录,然后再次用道具填充日志。如果我在this.setState中调用componentDidMount,则this.props的填充会出现在 third 渲染中。这是因为在this.setState中调用componentDidMount会触发更新前渲染。

我希望这很有意义并适用于您的情况-我问了您一个问题,以寻求解决类似行为的方法。