如何为某些字段排序API响应

问题描述 投票:0回答:1

我刚开始学习Reactjs并且已经停止了一些问题。我通过axios获取了某些API端点的数据(获取包含人口,货币,区域等数据的国家),我想对某些字段(例如地区或人口)的数据进行排序。

我认为在reactjs中做起来很简单,反应有一些内置的事情要做。但是,当我试图这样做,当我在谷歌搜索答案时,我真的暴露了。实现排序的最佳方法是什么?我怎样才能做到这一点?

我尝试过的:

import React, { Component } from 'react';
import axios from 'axios';
import './App.css';

class App extends Component {
  constructor(props){
      super(props)
      this.state={
          countries:[],

      }
  }

  componentDidMount(){
      axios.get('https://restcountries.eu/rest/v2/all')
      .then(response => {
          this.setState({

              countries:response.data

          })
      })
      .catch((error) => {
          console.log("error", error)
      })
  }

  render(){
      return(

          <div className = 'table'>

          <table>
          <tbody>
          <tr>
          <th>Country name </th>
          <th>Currencies</th>
          <th>Region </th>
          <th>Flag </th>
          <th >Population</th>
          <th>Languages</th>

          </tr>
          {
             this.state.countries.map((country,id) => {
                  return(

                      <tr className="tableRow">
                     <td> {country.name}</td>
                     <td>{country.currencies.map((currency,i)=>{
                     return (

                     <p>
                         <span>{currency.name} </span>

                         <span>{currency.symbol} </span>
                         </p>

                     )
                     })} </td>
                     <td> {country.region}</td>
                     <td> <img src={country.flag} alt={country.denonym}/> </td>
                     <td> {country.population} </td>
                     <td> {country.languages.map((language)=>{
                     return (
                         <span> {language.name} </span>
                     )
                     })} </td>
                      </tr>


                  )

              })

          }
          </tbody>

          </table>
          </div>

      )
  }
}

export default App;
javascript reactjs
1个回答
0
投票

基本上你需要做的是这样的事情:

...
this.state.countries.sort(/* Provide sort function here */).map((country,id) => {
...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

© www.soinside.com 2019 - 2024. All rights reserved.