首页 > 解决方案 > 我在 JSX 反应组件中获取数据时遇到问题

问题描述

我想从 swapi 获取数据并用这些数据做 jsx 组件,但是当我想使用这些数据时反应给我一个错误这是我的获取

var promise = await fetch('https://swapi.dev/api/people/1/')
  .then((res) =>  res.json() )
  .then(data => setLuke(data.data)) 

这是反应错误:

对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。 我不知道该怎么办你能帮我解决这个小问题吗

标签: javascriptreactjsfetchjsx

解决方案


You are probably rendering your promise var instead of {luke}. Also note that data will be a json object so you won't be able to render it directly. You will need to stringify it first. data.data which you are currently using will also be undefined. Just use data, it already contains the json.

await fetch("https://swapi.dev/api/people/1/")
      .then(res => res.json())
      .then(data => {
        setLuke(JSON.stringify(data));
      });

You should then be able to render it using {luke}


推荐阅读