javascript 在循环内对两个不同API请求作出React

e3bfsja2  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(113)

https://i.stack.imgur.com/RaoRC.jpghttps://i.stack.imgur.com/fPge5.jpg显示器
我用这个来获取两个不同的API。

***API #1***获取未按排名组织的名称***API #2***获取按排名组织的名称的ID,因此如果ID和名称匹配,则需要执行内部循环以获取玩家的名称。
我在异步函数上做了类似的事情

<script>
        getData();

        async function getData() {
            const response = await fetch('http://localhost:3008/api/highscore/players')
            console.log(response);
            const data = await response.json();
            const req = await fetch('http://localhost:3008/api/players')
            console.log(req);
            const info = await req.json();
            length = data.players.length;
            console.log(data);
            var temp = "";
            for (i = 0; i < length; i++)
                for (j = 0; j < length; j++)  {
                    {

                        if (info.players[i].id == data.players[j].id) {

                            temp += "<tr>";
                            temp += "<td>" + data.players[j].position + "</td>";
                            temp += "<td>" + info.players[i].name + "</td>";
                            temp += "<td>" + data.players[j].score + "</td>";
                            temp += "</tr>";
                        }

                    }
                }
            document.getElementById("data").innerHTML = temp;
        }

***这是我的React应用程序代码,我需要它做的地方:***我该如何去做呢?任何想法?任何帮助将不胜感激!

import axios from "axios";
import React, { useState, useEffect } from "react";

const Ranking = () => {
  const [playerName, setPlayerName] = useState([]);
  const [playerRank, setPlayerRank] = 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

        setPlayerName(allDataPlayer)
        setPlayerRank(getINFOPlayerRank)
      })
    )
  }

  useEffect(() => {
    fetchData()
  }, [])

  return (
    <table class="table table-bordered">
      <tr>
        <th>Rank</th>
        <th>Name</th>
        <th>Points</th>
      </tr>
        <tbody>
          {playerName?.map((name) => {
            return (
              <tr key={name.name}>
                <td>{name.name}</td>
              </tr>
            )
          })}
        </tbody>

    </table>
  )
}

export default Ranking
cld4siwp

cld4siwp1#

这是所呈现的内容output
您使用的是哪种后端语言?或者您正在使用远程服务器?这可以在后端完成,但前提是您可以访问它。Sping Boot 在这方面非常出色,使用ORM您可以轻松地使用@ManyToOne或@OneToMany关系Map表。如果您需要,我可以为您做这件事,请联系我。
如果你只是想继续你的代码,或者你正在从远程服务器获取响应,那么获取响应,把数据分别放在playerInf和rankInfo状态。直接在return方法中使用这段代码后:
//在您的应用中添加以下函数,替换url并在useEffect挂钩或您选择的函数中调用它们。

import React, {useState, useEffect} from 'react';
function App(props) {
    useEffect(()=> {
       // get the data from the website every 24 hours
       const intervalId = setInterval(() => {
          playerInfoData();
          playerRankData();
       }, 86400000);
       return ()=> {
            clearInterval(intervalId);
        };
    },[]);

    const playerInfoData = () => {
            fetch(`resources/jsons/player.json`,//replace your url here
                {   
                headers : { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }

            }).then(res => res.json()).then(
                data => {
                    setPlayerInfo(data);
                    setReady(true);

            }).catch(error => {
                console.log(error);
            });

        }
        const playerRankData = () => {
            fetch(`resources/jsons/rank.json`,
                {   
                headers : { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }

            }).then(res => res.json()).then(
                data => {
                    setRankInfo(data);
                    setReady(true);

            }).catch(error => {
                console.log(error);
            });
        }
    // ready is used to tell react to not render unless data is ready
    return (
    {ready && playerInfo.map(player => {

                    return (
                          <tr key={player.name}>
                            <td>{ready && rankInfo.map(rank => {
                                if(player.id === rank.id){
                                    return rank.value;
                                }
                            })
                            }</td>
                            <td>{player.name}</td>
                            <td>{player.points}</td>
                          </tr>
                        )
                      })
                  }
            )

}

再次重申,这不是一个好的做法,总是在后台做你的逻辑和自定义的响应。2我可以帮助你,如果你想知道更多,请联系我。

相关问题