FlatList数据前面的项目显示在列表底部[重复]

问题描述 投票:0回答:2

我在我的React Native应用程序中有这个FlatList组件,我正在尝试将项目添加到:

<FlatList
  data={this.state.comments}
  keyExtractor={this._keyExtractor}
  extraData={this.state}
  refreshing={this.state.refreshing}
  renderItem={({item, index}) => (
    <CardComment navigate={this.props.navigation.navigate} report={item.reply}/>
  )}
  removeClippedSubviews={false}
/>

我正在尝试更新列表并在当前注释的顶部放置一个新项目。在成功请求之后,这就是我在获取时所做的事情:

.then((r) => {
  this.setState({
    refreshing: false,
    loadingComments: false,
    comments: [
      {reply: r},
      ...comments,
    ],
  });
});

即使我将新元素添加到comments列表的开头,它仍然会出现在FlatList的底部。为什么,我该如何解决?

javascript android ios reactjs react-native
2个回答
-1
投票

你可以这样做:

const comments = this.state.comments.slice();
comments.unshift({ reply: 'Reply Q' });
this.setState({ comments: comments});

这将触发刷新。

以下显示了这如何解决您的问题... https://snack.expo.io/BkAi7StY-


0
投票

所以我发现了一些解决方法,而我似乎无法找到问题的答案。我保存了我以前的注释数组,setState来清理数组,这样我就可以清理整个FlatList组件。然后,在第一个setState的回调中,我将新元素追加到第一个数组的开头。

    comments = this.state.comments;
    this.setState({comments:[]}, function(){
      this.setState({
        comments: [
          {reply: r},
          ...comments,
        ],
        loadingComments: false,
      });
    });

不过,如果有人有更好的解决方案或知道我的问题的解决方案,请告诉我。 :)

更新:这实际上解决了我的问题:React Component's state renders strangely with .unshift(), but normal with .push()

© www.soinside.com 2019 - 2024. All rights reserved.