【问题标题】:How to sort list of objects within renerItem of flatlist?如何对平面列表的 renerItem 中的对象列表进行排序?
【发布时间】:2019-09-22 08:44:43
【问题描述】:

您好,我想对 renderItem 中的 FlatList 中的一个对象进行排序。我正在获取对象数组作为服务器响应。我想在这些对象中进行排序。我有一个带有价格的汽车列表。如果用户首先点击最低价汽车的排序按钮。我想在列表中首先显示最低价汽车。renderItem 中的item 结构如下。

单个item的展开结构如下。我想按其priceTotal对对象进行排序。

以下是我到目前为止所做的代码。请帮助找到解决方案。

示例代码

 renderItems = ({ item, index }) => {
    return (
          <CarReservationDetailComponent
            carName={item.make}
            carType={item.carType}
            carPrice1={item.priceTotal}
            mileage
            mileageText={item.autonomy + 'km. restantes'}
            imageUri={item.picture}
          />
        )
      }
    .....
    <FlatList
                  data={this.props.value.value}
                  renderItem={this.renderItems}
                  ItemSeparatorComponent={this.renderSeparator}
                  showsVerticalScrollIndicator={false}
                />

【问题讨论】:

  • 您可以从父组件传递一个回调函数,然后单击排序按钮父组件将排序项目列表。
  • 对不起,我没听明白。你能举个例子吗?

标签: javascript react-native sorting react-native-flatlist


【解决方案1】:

class ParentComponent extends Component {
  sortItemByKey = key => {
    const { items } = this.state;
    const clonedItems = items.map(item => ({ ...item }));
    clonedItems.sort(compare);
    this.setState({ items: clonedItems });

    function compare(a, b) {
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
      return 0;
    }
  };

  render() {
    const { items } = this.State;
    return (
      <View>
        <ChildComponent value={{ value: items }} sortByKey={this.sortItemByKey} />
      </View>
    );
  }
}

class ChildComponent extends Component {
  // you should bind this method to onclick of sort button
  onClick = () => {
    this.props.sortByKey('priceTotal');
  };

  render() {
    return (
      <FlatList
        data={this.props.value.value}
        renderItem={this.renderItems}
        ItemSeparatorComponent={this.renderSeparator}
        showsVerticalScrollIndicator={false}
      />
    );
  }
}

【讨论】:

  • 那么如何在renderItem中显示排序列表?
  • 对不起,我没有得到你。
  • 我的意思是在sortItemByKey 方法中我们将得到排序结果所以在FlatList的renderItem中排序结果将在item中对吗?
  • 是的,当我们对项目进行排序时。排序后的列表将作为道具传递给子组件,renderItem 方法将按排序顺序获取项目。
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多