简体   繁体   中英

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 . 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.

The following code works initially, but I can't figure out how to get it to update its 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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