【问题标题】:How to implement FlatList item counter如何实现 FlatList 项目计数器
【发布时间】:2021-08-24 03:57:54
【问题描述】:

我在 renderItem() 中过滤一个 FlatList。我正在检查一个属性,如果它存在,我会渲染该项目。我想实现一个计数器,这样我就知道我正在渲染多少项目,但是如果我尝试从 renderItem 设置状态,这会导致无限循环并且应用程序崩溃。我怎样才能最好地实施计数器?我是否需要在数据到达渲染之前过滤数据并从过滤器函数中增加计数器?

  const renderItem = ({item}) => {
    let categoryIds = map(item.locations[0].categories, 'categoryId');
    if (selectedCatId === -1 || categoryIds.includes(selectedCatId)) {
      // setCounter(counter+1) // can't do this
      return (
        <StoreListItem
          tenant={item}
          navigation={navigation}
          showLocation={showLocation}
        />
      );
    }
  };

【问题讨论】:

  • 你需要在 UI 的某个地方显示计数器吗?
  • 为什么你需要一个计数器的状态变量?只需使用普通的实例变量(let countedItems = ...this.countedItems = ...)?它仍然只是 JS,不要将状态用于非状态的东西(例如,不需要更新 UI 的东西)。
  • @NisanthReddy 是的。
  • @Mike'Pomax'Kamermans 这是一个功能组件。

标签: reactjs react-native


【解决方案1】:

你应该在你的组件中做这样的事情:

const renderedItems = itemsToRender.map(renderItem).filter(x => x)
return <div>
  Total items: {renderedItems.length}
  Here they are:
  {renderedItems}
</div>

.filter(x =&gt; x) 将过滤掉 undefined 的项目(当您的 renderItem 没有返回值时,项目将未定义,基本上是当您的 if 中的条件为 false 时)

别忘了在renderItem 中设置key 上的StoreListItem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多