React-Native ListView排序数据

时间:2018-09-05 22:50:46

标签: firebase listview react-native firebase-realtime-database

有人知道如何在react-native listview中对数据进行排序吗?

下面是我从firebase / database中检索的数据,我想按分数排序,然后呈现类似排行榜的内容。

(3) [{…}, {…}, {…}]
 0:
  data:{nome: "username", score: 100, status: "in"}
__proto__:Object
 1:{data: {…}}
 2:{data: {…}}
 length:3
__proto__:Array(0)

请参见以下代码:

class Leaderboards extends Component {

  componentWillMount() {
    this.props.leaderboards();
    this.criaFonteDeDados(this.props.leader);
  }

  componentWillReceiveProps(nextProps) {
    this.criaFonteDeDados(nextProps.leader);
  }

  criaFonteDeDados(leader) {
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    this.fonteDeDados = ds.cloneWithRows(leader);
  }

  renderRow(leader) {
    return (
      <View>
        <Text>{leader.data.score}</Text>
        <Text>{leader.data.nome}</Text>
      </View>
    );
  }

  render() {
    return (
      <ListView
        enableEmptySections
        dataSource={this.fonteDeDados}
        renderRow={this.renderRow}
      />
    );
  }
}

const mapStateToProps = state => {
  const leader = _.map(state.LeaderboardsReducer, (val) => {
    return { ...val };
  });
  return { leader };
};

export default connect(mapStateToProps, { leaderboards })(Leaderboards);

1 个答案:

答案 0 :(得分:2)

从firebase获取数据后,您必须对数组进行排序。要按分数排序,您应该有类似

data.sort(function(a,b) {
   return (a.score > b.score) ? 1 : ((b.score > a.score) ? -1 : 0);
});

然后不要忘记使用已排序的数组设置组件状态。