简体   繁体   English

React-Native根据父项更新ListView数据源

[英]React-Native Updating ListView DataSource Based on Parent Props

I'm working on an app that has a class that contains this: 我正在开发一个包含以下内容的类的应用程序:

<Details creature={this.state.creature} />

When the class updates its state, it updates the creature prop of Details . 当类更新其状态时,它将更新Detailscreature道具。 When this happens, I want Details to use the new creature prop to refresh the ListView using CREATURES[this.props.creature].food as the new DataSource. 发生这种情况时,我希望Details使用新的生物道具使用CREATURES[this.props.creature].food作为新的DataSource刷新ListView。

The following code works initially, but I can't figure out how to get it to update its dataSource: 以下代码最初可以工作,但我不知道如何获取它来更新其dataSource:

var Details = React.createClass({
  getInitialState: function(){
    var ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
    var cr = CREATURES[this.props.creature];
    var rows = cr.food;
    ds = ds.cloneWithRows(rows);
        return {
        dataSource:ds,
    };
    },
  renderRow: function(rowData){  
    return (
      <View>
         <Text>{rowData}</Text>
      </View>
    );
  },
  render: function(){
    return (
            <ListView
                    ref="listview"
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow}
                    automaticallyAdjustContentInsets={false}
                    keyboardDismissMode="on-drag"
                    keyboardShouldPersistTaps={true}
                    showsVerticalScrollIndicator={true}/>
    );
    }
});

Also, I'm a newbie, so I could be doing this a completely wrong way. 另外,我是新手,所以我可能会以完全错误的方式这样做。

You would use componentWillReceiveProps which passes the updates props and update your state with the updated data source for the list view. 您将使用componentWillReceiveProps,它传递更新道具并使用列表视图的更新数据源更新状态。

Something like (untested): 像(未经测试的):

componentWillReceiveProps: function(nextProps) {
    var cr = CREATURES[nextProps.creature];
    var rows = cr.food;
    var ds = this.state.datasource.cloneWithRows(rows);
    this.setState({
        ...this.state,
        dataSource: ds
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM