【问题标题】:React Native (Redux) FlatList jumping to top of list when onEndReached called调用 onEndReached 时 React Native (Redux) FlatList 跳转到列表顶部
【发布时间】:2019-03-09 19:18:35
【问题描述】:

我在 ReactNative 中有一个 FlatList,它从 API 中提取文章列表。当滚动到达列表末尾时,会从 API 中提取另一页文章,并将其附加到 Redux reducer 中的文章列表中。

FlatList 设置为:

render() {
    return(
    <FlatList data={this.props.articles.articles} // The initial articles list via Redux state
        renderItem={this.renderArticleListItem} // Just renders the list item.
        onEndReached={this.pageArticles.bind(this)} // Simply calls a Redux Action Creator/API
        onEndReachedThreshold={0}
        keyExtractor={item => item.id.toString()}/>
   )};

Redux 'articles' 状态对象使用 React Redux 连接函数映射到组件。相关的 reducer(为简洁起见删除了一些项目)如下所示:

/// Initial 'articles' state object
const INITIAL_STATE = {
    articles: [],
    loading: false,
    error: '',
    pageIndex: 0,
    pageSize: 10
};

export default(state = INITIAL_STATE, action) => {
switch(action.type){
    // The relevant part for returning articles from the API
    case ARTICLES_SUCCESS:
        return { ...state, loading: false, articles: state.articles.concat(action.payload.items), 
            pageIndex: action.payload.pageIndex, pageSize: action.payload.pageSize}
   default:
       return state;
   }
}

payload 是一个简单的对象——文章包含在action.payload.items 数组中,payload 中还有额外的分页信息(对于这个问题并不重要)。

API 返回正确数据后一切正常。

问题是,当滚动到达 FlatList 的末尾时,调用 API,新文章被拉好并附加到 this.props.articles 状态对象和 FlatList,但是 FlatList 跳转/滚动回列表中的第一项。

我认为问题可能在于我如何在 Redux reducer 中返回状态,但我不确定为什么。

使用concat返回新状态并附加新文章的正确方法吗?

【问题讨论】:

  • 你是如何连接数据的,更多细节会更有帮助,而且 onEndReached 会被多次调用,你在做什么来减少这种情况?
  • onEndReachedThreshold={0} 似乎是无效代码,不是吗?
  • 它在 ARTICLES_SUCCESS 情况下在减速器中连接。 onEndReachedThreshold={0} 据我所知很好。
  • 你找到解决方案了吗?
  • 目前有任何解决方案吗?

标签: react-native redux react-native-flatlist


【解决方案1】:

回答这个问题可能为时已晚,但我在将数据从 redux 提供给组件时遇到了完全相同的问题,并通过使我的组件成为普通的 Component 而不是 PureComponent 来解决跳跃效果使用shouldComponentUpdate生命周期钩子方法。对于您的组件,该方法应该是这样的:

shouldComponentUpdate(nextProps) {
   if (this.props.articles === nextProps.articles) {
       return false;
   }

   return true;
}

此方法(如果已实现)应返回一个布尔值,指示组件是否应更新。我在这里所做的是防止组件重新渲染,以防articles 的内容没有改变。

希望这对您或可能遇到类似问题的其他人有所帮助。

【讨论】:

    【解决方案2】:

    您需要添加到 listItem 样式的高度和宽度。冻结和跳跃可能是因为列表试图计算所有项目的大小,即使它们没有显示。

    您可以在以下网址找到答案:https://github.com/facebook/react-native/issues/13727

    【讨论】:

      【解决方案3】:

      使用 FlatList 作为组件并添加数据作为道具会重新渲染整个内容,因此它会滚动到顶部。我建议直接在您的页面中使用它并使用this.state 更改其数据,而不是props

      【讨论】:

      • 给出相同的结果
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2020-07-27
      • 2020-03-12
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多