axios 请求返回空数组

时间:2021-04-06 00:37:41

标签: javascript reactjs api axios

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 函数的第二个参数 [],它可以工作并返回数据每一秒。我应该怎么做才能获得一次数据?

0 个答案:

没有答案