在处理诺言时设定状态?

发布于 2025-02-11 06:03:29 字数 1079 浏览 0 评论 0原文

我一直在阅读有关此问题的堆栈溢出,并努力解决我的问题。我仍然很初中,所以我可能已经阅读了正确的修复程序,并且很密集地理解它。

该意图是从API查询中为返回对象设置的一个反应状态。

话虽如此,这是代码。编辑:修复了props

export const Background = ({background, setBackground}) => {
  //goal is to query a random land and set the background to the full art of that land on page load
  const backgroundQuery = async () => { 
    const query = "https://api.scryfall.com/cards/random?q=%28type%3Aland%29+is%3Aartcrop"
    const response = await fetch(query);
    console.log(response)
    const data = await response.json();
    console.log(data);
    setBackground(data);
  }

  return(
    <div>
      {background.length && <image src={background.image_uris.art_crop} alt="background image, basic full art mtg land"></image>}
      <button onClick={backgroundQuery}> Get Image </button>
    </div>
  )
};

console.log(数据)产生我想要的结果,但我知道我错误地解决了这一诺言。产生的错误如下:

Uncaught (in promise) TypeError: setBackground is not a function
    at backgroundQuery (Background.js:9:1)

I've been reading through Stack Overflow on this and struggling to solve my issue. I am still very junior, so I may have read the correct fix and been to dense to understand it.

The intention is set a piece of React state to the returned object from an API query.

That being said, here's the code. EDIT: fixed the props

export const Background = ({background, setBackground}) => {
  //goal is to query a random land and set the background to the full art of that land on page load
  const backgroundQuery = async () => { 
    const query = "https://api.scryfall.com/cards/random?q=%28type%3Aland%29+is%3Aartcrop"
    const response = await fetch(query);
    console.log(response)
    const data = await response.json();
    console.log(data);
    setBackground(data);
  }

  return(
    <div>
      {background.length && <image src={background.image_uris.art_crop} alt="background image, basic full art mtg land"></image>}
      <button onClick={backgroundQuery}> Get Image </button>
    </div>
  )
};

The console.log(data) yields the result I'd like, but I know I am incorrectly resolving this promise. The error yielded is below:

Uncaught (in promise) TypeError: setBackground is not a function
    at backgroundQuery (Background.js:9:1)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文