TypeError:获取外部API时无法读取React中未定义的属性'map'

时间:2020-06-02 18:20:58

标签: reactjs api

我正在尝试使用外部API来获取一些照片-在React中取消飞溅并得到错误=(请参见标题)。 API似乎完全可以正常工作,因为当我在控制台上登录该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;

1 个答案:

答案 0 :(得分:0)

查看API响应主体后,API回调应为:

<template>
    <div>
        <div v-for="(i, index) in divs" :key="index">
            <div :ref="'ref_' + index" @mouseover="divDragOver($event, index)">
                This is div {{ index }}
            </div>
        </div>        
    </div>
</template>

<script>

export default{
  methods: {
    divDragOver(e, i){
      var divTop = this.$refs["ref_" + i].getBoundingClientRect().top;
      console.log(divTop);
    }
  }
}
</script>

API响应正文中不存在setResult(response.data); 键。