【问题标题】:Uncaught ReferenceError data is not defined未定义未捕获的 ReferenceError 数据
【发布时间】:2023-01-16 05:10:01
【问题描述】:

我正在尝试将一个 API 获取到一个状态并使用 map 方法提供一个新数组。

但它给出了这个错误Uncaught ReferenceError data is not defined

这是代码-

const [games,setGAMES] = React.useState([])
const [gamesList,setGamesList] = React.useState([])
  React.useEffect(()=>{
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
        'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
      }
    };
    fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
      .then(response => response.json())
      .then( data => {setGAMES(data)})
      setGamesList( data.map( (object) => {
        return {
          name: object.title,
          link: object.game_url,
        }
      }))
    },[])
    

【问题讨论】:

    标签: reactjs api mapping


    【解决方案1】:

    setGamesList 函数正在从 .then 中调用,这导致了 not defined 错误。

    将功能移到块内,这应该可以工作。

    React.useEffect(()=>{
        const options = {
          method: 'GET',
          headers: {
            'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
            'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
          }
        };
        fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
          .then(response => response.json())
          .then( data => {
            setGAMES(data);
            setGamesList( data.map( (object) => {
              return {
                name: object.title,
                link: object.game_url,
              }
            }))
          })
        },[])
    

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 1970-01-01
      • 2023-01-23
      • 2013-03-22
      • 1970-01-01
      • 2016-11-03
      • 2011-01-05
      • 2016-01-02
      • 2013-10-06
      相关资源
      最近更新 更多