【问题标题】:React-Native Updating ListView DataSource Based on Parent PropsReact-Native 根据 Parent Props 更新 ListView 数据源
【发布时间】:2015-12-10 18:40:55
【问题描述】:

我正在开发一个应用程序,该应用程序的类包含以下内容:

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

当类更新其状态时,它会更新Detailscreature 属性。发生这种情况时,我希望 Details 使用新的生物道具来刷新 ListView,并使用 CREATURES[this.props.creature].food 作为新的 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}/>
    );
    }
});

另外,我是新手,所以我可能会以完全错误的方式这样做。

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您将使用 componentWillReceiveProps 传递更新道具并使用列表视图的更新数据源更新您的状态。

    类似的东西(未经测试):

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

    【讨论】:

    • 这比预期的要容易得多!工作完美。感谢您的快速回复!
    猜你喜欢
    • 2017-01-03
    • 2016-01-30
    • 2021-09-24
    • 2017-09-23
    • 2015-10-22
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多