【问题标题】:axios request return empty arrayaxios 请求返回空数组
【发布时间】:2021-04-06 00:37:41
【问题描述】:
import { useState, useEffect } from "react";

import "./App.css";
import Games from "./Components/games";
import Header from "./Components/header";
import Sidebar from "./Components/sidebar";
import axios from "axios";

function App() {
  const [gamesData, setGamesData] = useState([]);

  const options = {
    method: "GET",
    url: "https://rawg-video-games-database.p.rapidapi.com/games",
    headers: {
      "x-rapidapi-key": "920bb46b09msh9ae1555975a837bp1a6946jsn760df3d3a8e4",
      "x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
    },
  };

  useEffect(() => {
     axios
      .request(options)
      .then((response) => {
         setGamesData(response.data.results)
        console.log(gamesData);
      })
      .catch((error) => {
        console.error("error");
      });
  },[]);

  return (
    <div className="h-screen flex flex-col bg-gradient-to-r from-gray-700 via-gray-900 to-black">
      <Header />
      <div className="flex h-full ">
        <Sidebar />
        <Games />
      </div>
    </div>
  );
}

export default App;

嘿,伙计们有美好的一天。我尝试从 api 获取数据。但我尝试执行此方法,我得到空数组。如果我删除 useEffect 函数的第二个参数 [] 它工作并返回每个数据second.我应该怎么做才能获取一次数据?

【问题讨论】:

  • 状态变化是异步的,你不能在下一行console.log state 看到变化。在函数主体中打印您的状态以查看其最新值
  • 非常感谢先生,它工作正常。 @Jayce444

标签: javascript reactjs api axios


【解决方案1】:

我相信你只需要 App 组件中的console.loggamesData

import { useState, useEffect } from "react";

import "./App.css";
import Games from "./Components/games";
import Header from "./Components/header";
import Sidebar from "./Components/sidebar";
import axios from "axios";

function App() {
  const [gamesData, setGamesData] = useState([]);

  const options = {
    method: "GET",
    url: "https://rawg-video-games-database.p.rapidapi.com/games",
    headers: {
      "x-rapidapi-key": "920bb46b09msh9ae1555975a837bp1a6946jsn760df3d3a8e4",
      "x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
    },
  };

  useEffect(() => {
     axios
      .request(options)
      .then((response) => {
         setGamesData(response.data.results)
      })
      .catch((error) => {
        console.error("error");
      });
  },[]);

  console.log(gamesData);

  return (
    <div className="h-screen flex flex-col bg-gradient-to-r from-gray-700 via-gray-900 to-black">
      <Header />
      <div className="flex h-full ">
        <Sidebar />
        <Games />
      </div>
    </div>
  );
}

export default App;

附:您已经在上面发布的代码 sn-p 中公开了您的 API 密钥。这是一个敏感的凭证。我建议您现在删除此密钥并从 RapidAPI 开发人员仪表板生成一个新密钥。

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 2021-01-27
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    相关资源
    最近更新 更多