axios React无法读取页面刷新后获取的数据

e4eetjau  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(102)

我一直在尝试将这些数据从https://bad-api-assignment.reaktor.com/rps/history获取到我的node.js后端,并将其显示在我的React前端。
我可以以某种方式使它工作并在控制台上看到数据,但当刷新前端页面时,当我试图再次处理数据时,我会得到这样的错误:
x1c 0d1x的数据
App.js:

import axios from "axios";
import React from "react";
import GameData from "./GameData";

export default function App() {
  const [games, getGames] = React.useState(null);
  const baseURL = "http://localhost:5000";

    React.useEffect(() => {
       getAllGames();
    }, []);

    const getAllGames = async () => {
        await axios.get(baseURL)
        .then((response) => {
            const allGames = response.data.data;
            //console.log(allGames)
            getGames(allGames);
        })
        .catch(error => console.error('Error: $(error'));
    }
        return(
            <GameData games={games}/>
        )
}

字符串
GameData.js:

import React from 'react';

export default function GameData(props) {
    const displayGames = (props) => {
        const {games} = props;

        console.log(games)

        games.map((game, index) => {
            console.log(game, index);
                return(
                    <div className='game' key={game.type}>
                    </div>
                )
        }
        )
    }
    return(
        <>
        {displayGames(props)}
        </>
    )
}


在GameData.js上,如果我评论这一节:

//games.map((game, index) => {
//  console.log(game, index);
//      return(
//          <div className='game' key={game.type}>
//          </div>
//      )
//}
//)


我可以在我的控制台上看到console.log(games)。然后我可以取消注解这些行并保存在React上,它将在控制台上显示Map的数据:



好的,太完美了,它可以按照我的意愿工作,但是如果我在浏览器上刷新页面,我将面临error/null问题



我一直在谷歌搜索,但无法找到它。如何解决这样的问题?我以后也可以对这些数据进行排序等等。
希望它有意义。

8e2ybdfx

8e2ybdfx1#

首先检查数组是否不为空,然后循环遍历它:

//GameData.js
export default function GameData({ games }) {
return(
    <>
    {games.length > 0 && games.map((item) => (
        <div key={item.id}>
               {item.name}
         </div>
      ))
    </>
)

字符串
}

相关问题