开发者问题收集

如何将 API 结果显示出来?

2021-02-09
212

当我从 API 获取数据时,会发生此错误。

TypeError: Cannot read property 'length' of undefined

以下代码代表我的项目的主页。我想在主页上显示 20 个数组项。

App.js

import React, { useState, useEffect } from "react" 
import banner from "./assets/marvel-group.jpg"    
import Details from "./components/details"

const CHARACTERS_API =
  "https://gateway.marvel.com:443/v1/public/characters?ts=thesoer&apikey=dkauyjs586ddh&hash=4b59bfb18ff6660c1f6alimit=20"

const theme = createMuiTheme({
  palette: {
    primary: {
      main: "#202020",
    },
  },
})

function App() {
  const classes = useStyles()

  const [characters, setCharacters] = useState([])

  useEffect(() => {
    fetch(CHARACTERS_API)
      .then((res) => res.json())
      .then((data) => {
        console.log(data)
        setCharacters(data.results)
      })
  }, [])

  return (
    <>
      <div>
        <img src={banner} alt="banner" width="100%" height="50%" />
      </div>
      <div>
        {characters.length > 0 && characters.map((character) => <Details />)}
      </div>
    </>
  )
}

export default App

Details.js

import React from "react"

const Details = () => <div>character</div>

export default Details

这是 API 数据。

在此处输入图片描述

3个回答

我猜测 data.response 未定义,这就是你收到错误的原因。

试试这个:

useEffect(() => {
    fetch(CHARACTERS_API)
      .then((res) => res.json())
      .then((data) => {
        console.log(data)
        setCharacters(data.data.results)
      })
  }, [])
Borjante
2021-02-09

这可能适用于您的情况,您可以尝试一次,只需在 characters.length 前面添加字符

 <div>
            {characters && characters.length > 0 && characters.map((character) => <Details />)}
    </div>
Varun Pradhan
2021-02-09

使用此运算符 https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Optional_chaining 或其他

characters && (characters.length > 0 && characters.map((character) => <Details />)
KolisbikBoh
2021-02-09