React Native SectionList / ListView视图desc排序顺序未维护

时间:2017-04-20 01:18:53

标签: javascript sorting listview reactjs react-native

我想这更像是对javascript排序的理解或者如何在SectionList或ListView中呈现节。我有一个数据源,我需要以ageGroup的desc顺序显示结果。我的行对象有:

[{name: 'Saurabh', ageGroup:'1'}, {name: 'John', ageGroup:'0'}]

当我按年龄组对它进行排序时,我可以正确地看到排序,但是当我将这个排序的数组传递给节标题时,排序顺序就会丢失。但是,如果我将ageGroup更改为字符而不是数字表示将0替换为A而将1替换为B. 到目前为止,这是我的代码 - 之前我尝试使用sectionHeaders的ListView,稍后将其更改为SectionList,但它无论如何都无法正常工作。如何按ageGroup的降序呈现列表元素?

这是我的代码:

import React, {
  Component
} from 'react';
import {
  Text,
  SectionList
} from 'react-native';

import _ from 'lodash';

let dataSource = [{
    name: 'Saurabh',
    ageGroup: '1'
  },
  {
    name: 'John',
    ageGroup: '0'
  },
  {
    name: 'Alex',
    ageGroup: '1'
  },
]

// let dataSource = [{
//     name: 'Saurabh',
//     ageGroup: 'B'
//   },
//   {
//     name: 'John',
//     ageGroup: 'A'
//   },
//   {
//     name: 'Alex',
//     ageGroup: 'B'
//   },
// ]


dataSource = _.orderBy(dataSource, ['ageGroup'], ['desc']);
// dataSource = dataSource.sort((a,b) => b-a);

console.log('dataSource: ' + JSON.stringify(dataSource));

dataSource = _.groupBy(dataSource, d => d.ageGroup);
dataSource = _.reduce(dataSource, (acc, next, index) => {
  acc.push({
    key: index,
    data: next
  })
  return acc
}, []);
console.log('dataSource: ' + JSON.stringify(dataSource));

export default class SectionListExample extends Component {
  constructor(props) {
    super(props);
    this.renderItem = this.renderItem.bind(this);
    this.renderSectionHeader = this.renderSectionHeader.bind(this);
  }


  renderItem(item) {
    return ( <
      Text style = {
        {
          fontSize: 14,
          color: 'blue'
        }
      } > {
        item.item.name
      } < /Text>
    );
  }


  renderSectionHeader(headerItem) {
    return ( <
      Text style = {
        {
          fontSize: 20,
          fontWeight: '700',
          color: 'gray'
        }
      } > {
        headerItem.section.key
      } < /Text>
    );
  }


  render() {

    return ( <
      SectionList renderItem = {
        this.renderItem
      }
      renderSectionHeader = {
        this.renderSectionHeader
      }
      sections = {
        dataSource
      }
      keyExtractor = {
        (item) => item.name
      }
      removeClippedSubviews = {
        false
      }
      style = {
        {
          flex: 1,
          marginTop: 100
        }
      }
      />
    );
  }
}

0 个答案:

没有答案