首页 > 解决方案 > react-native 排序功能在 FlatList 中不起作用

问题描述

嗨,我正在使用 react-native 创建一个排序功能


我正在使用Flatlist来显示列表项。当我在模拟器和网络中运行时,控制台中没有显示错误,但排序功能不起作用。

我的代码在下面请检查

  import React, { Component } from 'react';
import contacts,{ compareNames } from './contacts'
import Card from './Card'
import {
  View,
  Button,
  StyleSheet,
  FlatList,
} from 'react-native';


const styles = StyleSheet.create({
  mainwrap: {
    display:'flex',
    flexGrow: 1,
    justifyContent: 'space-between',
    paddingBottom:30,

  },
  txtheading:{
    backgroundColor:'black',
    margin:'auto',
    marginTop:50,
  },
  scollitms:{
    display:'flex',
    flex:1,
    position:'relative'
  }
});
export default class App extends Component {
  state = {
    showCounter: true,
    contacts:contacts
  }
  toggglecounter = () => {
    this.setState((prev) => ({showCounter: !prev.showCounter}))
  }
  sorting = () => {
    this.setState((prev) => ({
      contacts: [...prev.contacts].sort(compareNames)
    }))
  }
  renderItem = ({item}) => (<Card key={item.id} {...item} />)
  render() {
      return (
        <View style={[styles.mainwrap]}>
          <View style={[styles.marginfromtop , styles.countfont, styles.txtheading]}>
            <Button style={{ marginTop: 50, zIndex:999}} onPress={this.toggglecounter} title="Toggle Contacts" />
            <Button onPress={this.sorting} title="sort" />
          </View>
         {this.state.showCounter ?
          <FlatList  style={[styles.scollitms]}
            data={this.state.contacts}
            renderItem={this.renderItem}
            keyExtractor={item => item.key.toString()}
          />
          : null
          }
      </View>
    );
  }
}

下面是我正在调用的排序函数

export const compareNames = (contact1, contact2) => contact1.name > contact2.name

标签: reactjsreact-nativeecmascript-6

解决方案


推荐阅读