reactjs 对React JS上的Map数组进行排序

afdcj2ne  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(257)

我从这两个在线API中获取数据,第一个API是随机组织的,第二个API是按等级组织的,当两个API放在一起时,我得到的数据结果是***API#2***位置,***API#1***名称,***API#2***点,但按***API#1***随机组织。
[1]

我怎样才能sort().map我的代码,使表上的结果按1、2、3等排序来组织?
密码:

import axios from "axios";
import React, { useState, useEffect } from "react";
import Pagination from "https://cdn.skypack.dev/rc-pagination@3.1.15";

const News = () => {
  const [playerName, setPlayerName] = useState([]);
  const [playerRank, setPlayerRank] = useState([]);
  const [player, setPlayer] = useState([]);
  const [perPage, setPerPage] = useState(10);
  const [size, setSize] = useState(perPage);
  const [current, setCurrent] = useState(1);
  const [players, setPlayers] = useState();

  const fetchData = () => {
    const playerAPI = 'http://localhost:3008/api/players';
    const playerRank = 'http://localhost:3008/api/highscore/players';

    const getINFOPlayer = axios.get(playerAPI)
    const getPlayerRank = axios.get(playerRank)
    axios.all([getINFOPlayer, getPlayerRank]).then(
      axios.spread((...allData) => {
        const allDataPlayer = allData[0].data.players
        const getINFOPlayerRank = allData[1].data.players
        const newPlayer = allDataPlayer.map(name => {
          const pr = getINFOPlayerRank.find(rank => name.id === rank.id)

          return {
            id: name.id,
            name: name.name,
            status: name.status,
            position: pr?.position,
            score: pr?.score
          }

          // or simply do the following if the keys doesn't matter: return {...name, ...pr}
        })

        setPlayerName(allDataPlayer)
        setPlayerRank(getINFOPlayerRank)

        console.log(newPlayer)
        setPlayer(newPlayer)
      })
    )
  }
  useEffect(() => {
    fetchData()
  }, [])

  const PerPageChange = (value) => {
    setSize(value);
    const newPerPage = Math.ceil(players.length / value);
    if (current > newPerPage) {
      setCurrent(newPerPage);
    }
  }

  const getData = (current, pageSize) => {
    // Normally you should get the data from the server
    return player?.slice((current - 1) * pageSize, current * pageSize);
  };

  const sortData = getData && player?.sort((a, b) => a.position > b.position ? 1 : -1)

  const PaginationChange = (page, pageSize) => {
    setCurrent(page);
    setSize(pageSize)
  }

  const PrevNextArrow = (current, type, originalElement) => {
    if (type === 'prev') {
      return <button><i className="fa fa-angle-double-left"></i></button>;
    }
    if (type === 'next') {
      return <button><i className="fa fa-angle-double-right"></i></button>;
    }
    return originalElement;
  }

  return (
    <>
      <div className="container-fluid mt-5 mb-5">
        <div className="row justify-content-center">
          <div className="col-md-10">
            <div className="card">
              <div className="card-body p-0">

                <div className="table-filter-info">

                  <Pagination
                    className="pagination-data"
                    showTotal={(total, range) => `Showing ${range[0]}-${range[1]} of ${total}`}
                    onChange={PaginationChange}
                    total={player.length}
                    current={current}
                    pageSize={size}
                    showSizeChanger={false}
                    itemRender={PrevNextArrow}
                    onShowSizeChange={PerPageChange}
                  />
                </div>
                <div className="table-responsive">
                  <table className="table table-text-small mb-0">
                    <thead className="thead-primary table-sorting">
                      <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Points</th>
                        <th>Alliance</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {getData(current, size)
                        .map((player) => {
                          return (
                            <tr key={player.name}>
                              <td>{player.position}</td>
                              <td>{player.name}</td>
                              <td>{player.score}</td>
                              <td>{player.alliance}</td>
                              <td>{player.status}</td>
                            </tr>
                          );
                        })}
                    </tbody>
                  </table>
                </div>
                <div className="table-filter-info">

                  <Pagination
                    className="pagination-data"
                    showTotal={(total, range) => `Showing ${range[0]}-${range[1]} of ${total}`}
                    onChange={PaginationChange}
                    total={player.length}
                    current={current}
                    pageSize={size}
                    showSizeChanger={false}
                    itemRender={PrevNextArrow}
                    onShowSizeChange={PerPageChange}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export default News
rbl8hiat

rbl8hiat1#

要对ReactJS中任何数据进行排序,只需使用以下代码-

const sortData = apiData && apiData.sort((a, b) => a.name > b.name ? 1 : -1)

在上面的代码中,ApiData是排序的,你可以用获取数据的常量名来改变它。在使用排序方法之后,只需调用两个值,如a和b,然后比较它们并返回结果。你也可以a.name用***pr?.position***来改变www.example.com,以便对API结果进行排序。
希望你会喜欢这个例子,并解决你的问题。如果你仍然面临的问题让我知道,我会帮助你更多。谢谢

相关问题