首页 > 解决方案 > TypeError:在获取外部 API 时无法读取 React 中未定义的属性“地图”

问题描述

我正在尝试使用外部 API - Unsplash in React 获取一些照片并得到错误 =(见标题)。API 似乎工作得很好,因为当我在控制台记录它时,但不知何故我无法将它打印出来。你能看看我是否在某个地方犯了错误吗?我真的迷路了,已经花了几个小时试图弄清楚。

这是我的代码:

import React, { useState } from "react";
import axios from "axios";


const PhotoList = () => {
  const [photography, setPhotography] = useState("");
  const [clientId, setClientId] = useState(
    "MyAPIKey"
  );
  const [result, setResult] = useState([]);

  const handleChange = ev => {
    setPhotography(ev.target.value);
  };
  const handleSubmit = ev => {
    console.log(photography);

    const url =
      "https://api.unsplash.com/photos?page=1&query" +
      photography +
      "&client_id=" +
      clientId;

    axios.get(url).then(response => {
      console.log(response);
      setResult(response.data.results);
    });
  };

并返回 HTML :

  return (
    <>
      <h1>Here is the list of the photos</h1>
      <input
        onChange={handleChange}
        type="text"
        name="photography"
        placeholder="Get more inspiration here"
      ></input>
      <button onClick={handleSubmit} type="submit">
        Search
      </button>

      {result.map(photography => (
        <img src={photography.urls.small} />
      ))}
    </>
  );
};

export default PhotoList;

标签: reactjsapi

解决方案


查看 API 响应正文后,API 回调应为:

setResult(response.data);

API 响应正文中results不存在密钥。


推荐阅读