【问题标题】:Issue displaying data from API显示来自 API 的数据的问题
【发布时间】:2022-01-10 12:16:37
【问题描述】:

我在显示从 API 获取的数据时遇到问题,我真的不知道这里出了什么问题...

我尝试使用 map() 函数来访问数据,但它也没有按预期工作

import React from "react";
import axios from 'axios';

const options = {
      method: 'GET',
      headers: {
        Accept: 'application/json',
            Authorization: 'API_KEY'
      }
};

export default class List extends React.Component {
    state = {
        locations: []
    }

    componentDidMount() {
        axios.get('https://api.foursquare.com/v3/places/search?query=gallery%20&ll=48.85%2C2.35&radius=10000&categories=10004&sort=DISTANCE', options)
            .then(res => {
                const locations = res.data;
                console.log(locations.results)
                return this.setState({ locations });
            })
    }

    render() {
        return (
            <div>
               
            <ul>
               <div>{this.state.locations.results}</div>
            </ul>
            </div>
        )
    }
} 

这两个错误出现了

1: 错误:对象作为 React 子对象无效(发现:具有键 {fsq_id, categories,chains, distance, geocodes, location, name, related_places} 的对象)。如果您打算渲染一组子项,请改用数组

2: Unhandled Promise Rejection: Error: Objects are not valid as a React child (found: object with keys {fsq_id, categories, chain, distance, geocodes, location, name, related_places})。如果您打算渲染一组孩子...

这是我在日志中找回的对象:

Log File

任何线索都会非常有帮助,谢谢! :)

【问题讨论】:

  • 也许贴一个你得到的对象的例子?
  • 请。不要使用屏幕截图(和图像)作为示例数据。使用可以复制到答案的东西 - 轻松。帮助 SO 成员,让他们帮助您!

标签: javascript reactjs api


【解决方案1】:

根据屏幕截图,您会得到一个数组。 React/JSX 不只是把数组放在外面,你需要遍历它。这是一个带有功能组件和自定义钩子的 sn-p:

const { useEffect, useState } = React

const useFetchData = () => {
  const [response, setResponse] = useState([])
  const [loading, setLoading] = useState(false)
  
  useEffect(() => {
    setLoading(() => true)
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(json => setResponse(() => json))
      .finally(setLoading(() => false))
  })
  
  return { response, loading }
}

const App = () => {
  const { response, loading } = useFetchData()
  return (
    <div>
      {
        response.length && !loading
        ? response.map(({ id, name, username }) => {
          return (
            <div key={id}>{id} - {name} - {username}</div>
          )
        })
        : "Loading users..."
      }
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

虽然您在示例中使用了一个类组件,并且这是我的 sn-p 中的一个功能组件,但基本思想是相同的:如果您想在 JSX 中显示一个项目数组,那么您需要对它们进行迭代使用实际上返回 JSX 元素的迭代器函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 2020-03-12
    • 2021-09-26
    • 2020-08-28
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多