当数组中元素的值发生变化时,React-Native 更新 UI,而不使用 ForceUpdate

React-Native update UI when value on element in array changes, without using ForceUpdate

想象一下:我有一个 FlatList 显示消息线程列表。每个单元格都有一个标签,显示该线程中的新消息数。每个单元格还显示该线程中最新消息的截断字符串。还介绍了其他内容。线程列表保存在 redux 中,并设置为我的 FlatList 的数据属性。线程的 class 实例不知道 FlatList 并且当某些事情发生变化时不能强制重新加载它,例如一条新消息进来(有意设计)。现在的问题是 FlatList 在发生此类事件时不会更新。它仅在设置新线程数组(新实例)时更新。

当线程中的任何值发生变化时,如何让 FlatList 更新?

不推荐定时重复加载。我正在考虑让线程更新(通过增加)redux 中的一个名为 MessageThreadUpdateCount 的值,这将是一个数字。每次 UI 连接的值发生变化时都会这样做。 FlatList 然后使用该 redux 值作为其 ExtraData 属性。因此在发生变化时进行更新。使用布尔值而不是数字会引发一个问题:什么应该将它设置为 false,什么时候?还有其他建议吗?

要更新列表,您需要设置 FlatList 组件的 'extraData' 属性,

This is a PureComponent which means that it will not re-render if props remain shallow- equal. Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes. This includes the data prop and parent component state.

举例

 <FlatList
    data={this.props.data}
    extraData={this.state}
    keyExtractor={this._keyExtractor}
    renderItem={this._renderItem}
  />

当您收到新消息时,您的状态正在改变。请注意,您可以用收到新消息时更新的任何变量替换 'this.state' 例如,消息可能是一个计数器。

(来源:https://facebook.github.io/react-native/docs/flatlist.html

希望对您有所帮助。