【问题标题】:I have a problem with fetching data with useEffect我在使用 useEffect 获取数据时遇到问题
【发布时间】:2022-01-24 00:06:11
【问题描述】:

这是我的代码。

import React from 'react'
import { useEffect, useState } from 'react';
import './style.css'

function App(){

  let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
      "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
  })

  useEffect(()=>{


    (async function(){
      let data = await fetch(api).then(res=>res.json());
      console.log(data);
    })();
  },[api]);
return(
  <div>Test</div>
);

};
export default App;

这是我遇到的错误。

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

它适用于其他简单的 api 调用,如“https://www.breakbadapi.com/api/”,但它不适用于我正在使用的这个 api,我不知道为什么。

【问题讨论】:

  • 效果很好,但是如果我想使用“api”作为函数参数呢?

标签: javascript reactjs


【解决方案1】:
let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
        "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
})

您使用的是comma operator,因此api 将只包含出现在该网址之后的对象。

将此存储为对象或数组:

const api = ["https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
        "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
}]


function App() {
    useEffect(() => {
        (async function () {
            const [url, options] = api;
            let data = await fetch(url, options).then(res => res.json());
            console.log(data);
        })();
    }, []); // this can be empty as api is outside and doesn't change

    return (
        <div>Test</div>
    );

};

【讨论】:

  • 它工作得很好,谢谢,但是我怎样才能使用 api 作为参数,以便我可以在其他文件中使用我要传递的 api?
  • 您可以在单独的文件中定义api,将其导出,然后在需要的地方导入
猜你喜欢
  • 1970-01-01
  • 2021-03-03
  • 2020-12-11
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多