【问题标题】:React Native: Update ListView Row when props changesReact Native:当道具更改时更新 ListView Row
【发布时间】:2017-09-28 03:17:55
【问题描述】:

我确实有一个带有renderRow() 函数的 ListView 组件。我的自定义 ListBountiesView 组件呈现 ListView Row 还采用名为 cr 的道具,并根据 cr 的值在每一行中显示一些内容。

问题是当this.props.customerRelationship 改变它的值时,ListView 行没有得到更新。

我正在这样做:this.props.customerRelationship.points += responseJson.points;

我猜ListView 仅在data 属性更改时更新,但我怎样才能将道具移动到我的 renderRow 组件以便它们也更新 ListView?

SuperScreen.js

renderRow(bounty) {
  const { customerRelationship } = this.props;
  return (
    <ListBountiesView
      key={bounty.id}
      bounty={bounty}
      cr={customerRelationship}
      onPress={this.openDetailsScreen}
    />
  );
}

render() {
    const { bounties } = this.props;

    return (
      <ListView
          data={bounties}
          renderRow={this.renderRow}
          loading={loading}
      />
    )

【问题讨论】:

  • 您不会在任何地方更新您的dataSource,这就是它不会改变的原因。正如其他人所建议的那样,您需要使用其他生命周期事件来捕获更改。或者,您可以考虑使用 FlatList ,它不需要您设置 dataSource 对象并且只需要一个数组 - 这样当您的道具更改时它会自动更新。

标签: react-native react-native-listview shoutem


【解决方案1】:

data prop 获得新的引用时,ListView 会刷新数据源:

 componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setState({ dataSource: this.listDataSource.clone(nextProps.data) });
    }

    if (nextProps.loading !== this.props.loading) {
      this.setLoading(nextProps.loading);
    }
  }

同样,React Native 的 ListView 会在其数据源发生变化时刷新。这在他们的 GitHub 和许多其他线程中进行了讨论。普遍接受的解决方法是创建一个新的数据数组。在您的情况下,只要 customerRelationship 更改,请在 componentWillReceiveProps 中执行此操作。

【讨论】:

  • cloneWithRows
【解决方案2】:

将您的 customerRelationship 移动到 bounty 对象。每个bounty 都应该有这个属性,然后检查它的值在rowHasChanged 中的变化。另一种方法是在componentWillReceiveProps 函数中检查customerRelationship,如果它的值更改克隆bounties,那么它的所有子对象都有新的对象引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2016-03-09
    相关资源
    最近更新 更多