【问题标题】:React Cant read fetched data after page refresh页面刷新后反应无法读取获取的数据
【发布时间】:2022-01-07 12:23:17
【问题描述】:

所以我一直在尝试从 https://bad-api-assignment.reaktor.com/rps/history 获取这些数据到我的 node.js 后端并将其显示在我的 React 前端。

我可以通过某种方式使其工作并在控制台中查看数据,但是在刷新前端页面时,再次尝试处理数据时会出现这样的错误:

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 上,它会在控制台上显示映射数据: Console after un-commenting code and saving on React.

好吧,太完美了,它可以按我的意愿工作,但是如果我在浏览器上刷新页面,我将面临错误/空问题Console error messages after page refresh

我一直在尝试用谷歌搜索,但无法弄清楚。如何解决这样的问题?以后我应该也可以对这些数据进行排序,依此类推。

希望它有意义。

【问题讨论】:

  • 这是一个非常常见的初学者错误,它只是由const [games, getGames] = React.useState(null); 而不是正确的const [games, getGames] = React.useState([]); 引起的 我还建议使用setGames 的正确命名约定,因为它是一个setter 方法,而不是吸气剂。
  • 数据是异步的,所以你应该添加检查条件games &amp;&amp; games.map()=&gt;,道具变得不确定,因为页面被渲染然后api的数据被命中,然后它被存储在games alos更改将状态设置为一个空数组useState([])
  • 错误原因是games.map被命中,而gamesnull
  • 感谢所有 cmets 以及我未能正确获取图像的编辑! @ChrisG 谢谢!将 null 更改为数组解决了我的问题,我同意 getGames-->setGames!

标签: javascript reactjs api axios fetch


【解决方案1】:

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

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 2022-10-25
    • 2018-05-21
    • 2017-02-20
    相关资源
    最近更新 更多