首页 > 解决方案 > 使用 axios react 从 superhero api 获取数据

问题描述

我需要在 React 应用程序中使用 Axios从https://superheroapi.com/获取数据。我在控制台中没有任何警告消息,但仍然没有获取数据。页面加载器正在加载,但没有响应。

这是我的代码。

应用程序.jsx

import React, { useState } from 'react';
import './App.css';
import {
  InputGroup,
  Input,
  InputGroupAddon,
  Button,
  FormGroup,
  Label,
  Spinner
} from 'reactstrap';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.min.css';
import axios from 'axios';
import BookCard from './BookCard.jsx';
function App() {
  // States
  const [maxResults, setMaxResults] = useState(10);
  const [startIndex, setStartIndex] = useState(1);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [cards, setCards] = useState([]);
  // Handle Search
  const handleSubmit = () => {
    setLoading(**false**);
    if (maxResults > 40 || maxResults < 1) {
      toast.error('max results must be between 1 and 40');
    } else {
      axios
        .get(
           
          `https://www.superheroapi.com/api.php/my-api-key/search/${query}&maxResults=${maxResults}&startIndex=${startIndex}`

        )
        .then(res => {
          if (startIndex >= res.data.totalItems || startIndex < 1) {
            toast.error(
              `max reults must be between 1 and ${res.data.totalItems}`
            );
          } else {
            if (res.data.items.length > 0) {
              setCards(res.data.items);
              setLoading(false);
            }
          }
        })
        .catch(err => {
          setLoading(true);
          console.log(err.response);
        });
    }
  };
  // Main Show Case
  const mainHeader = () => {
    return (
      <div className='main-image d-flex justify-content-center align-items-center flex-column'>
        {/* Overlay */}
        <div className='filter'></div>
        <h1
          className='display-2 text-center text-white mb-3'
          style={{ zIndex: 2 }}
        >
          Search
        <div style={{ width: '60%', zIndex: 2 }}>
          <InputGroup size='lg' className='mb-3'>
            <Input
              placeholder='Book Search'
              value={query}
              onChange={e => setQuery(e.target.value)}
            />
            <InputGroupAddon addonType='append'>
              <Button color='secondary' onClick={handleSubmit}>
                <i className='fas fa-search'></i>
              </Button>
            </InputGroupAddon>
          </InputGroup>
          <div className='d-flex text-white justify-content-center'>
            <FormGroup >
              <Label for='maxResults'>Max Results</Label>
              <Input
                type='number'
                id='maxResults'
                placeholder='Max Results'
                value={maxResults}
                onChange={e => setMaxResults(e.target.value)}
              />
            </FormGroup>
            <FormGroup className='ml-5'>
              <Label for='startIndex'>Start Index</Label>
              <Input
                type='number'
                id='startIndex'
                placeholder='Start Index'
                value={startIndex}
                onChange={e => setStartIndex(e.target.value)}
              />
            </FormGroup>
          </div>
        </div>
      </div>
    );
  };

  const handleCards = () => {
    if (loading) {
      return (
        <div className='d-flex justify-content-center mt-3'>
          <Spinner style={{ width: '3rem', height: '3rem' }} />
        </div>
      );
    } else {
      const items = cards.map((item, i) => {
        let thumbnail = '';
        if (item.volumeInfo.imageLinks) {
          thumbnail = item.volumeInfo.imageLinks.thumbnail;
        }

        return (
          <div className='col-lg-4 mb-3' key={item.id}>
            <BookCard
              thumbnail={thumbnail}
              title={item.volumeInfo.name}
        
            />
          </div>
        );
      });
      return (
        <div className='container my-5'>
          <div className='row'>{items}</div>
        </div>
      );
    }
  };
  return (
    <div className='w-100 h-100'>
      {mainHeader()}
      {handleCards()}
      <ToastContainer />
    </div>
  );
}

export default App;

这是我在浏览器中运行 url ( https://www.superheroapi.com/api.php/my-api-key/search/batman ) 时的 json 输出

{
    "response": "success",
    "results-for": "batman",
    "results": [{
        "id": "69",
        "name": "Batman",
        "powerstats": {
            "intelligence": "81",
            "strength": "40",
            "speed": "29",
            "durability": "55",
            "power": "63",
            "combat": "90"
        },
        "biography": {
            "full-name": "Terry McGinnis",
            "alter-egos": "No alter egos found.",
            "aliases": ["Batman II", "The Tomorrow Knight", "The second Dark Knight", "The Dark Knight of Tomorrow", "Batman Beyond"],
            "place-of-birth": "Gotham City, 25th Century",
            "first-appearance": "Batman Beyond #1",
            "publisher": "DC Comics",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["5'10", "178 cm"],
            "weight": ["170 lb", "77 kg"],
            "eye-color": "Blue",
            "hair-color": "Black"
        },
        "work": {
            "occupation": "-",
            "base": "21st Century Gotham City"
        },
        "connections": {
            "group-affiliation": "Batman Family, Justice League Unlimited",
            "relatives": "Bruce Wayne (biological father), Warren McGinnis (father, deceased), Mary McGinnis (mother), Matt McGinnis (brother)"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/10441.jpg"
        }
    }, {
        "id": "70",
        "name": "Batman",
        "powerstats": {
            "intelligence": "100",
            "strength": "26",
            "speed": "27",
            "durability": "50",
            "power": "47",
            "combat": "100"
        },
        "biography": {
            "full-name": "Bruce Wayne",
            "alter-egos": "No alter egos found.",
            "aliases": ["Insider", "Matches Malone"],
            "place-of-birth": "Crest Hill, Bristol Township; Gotham County",
            "first-appearance": "Detective Comics #27",
            "publisher": "DC Comics",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["6'2", "188 cm"],
            "weight": ["210 lb", "95 kg"],
            "eye-color": "blue",
            "hair-color": "black"
        },
        "work": {
            "occupation": "Businessman",
            "base": "Batcave, Stately Wayne Manor, Gotham City; Hall of Justice, Justice League Watchtower"
        },
        "connections": {
            "group-affiliation": "Batman Family, Batman Incorporated, Justice League, Outsiders, Wayne Enterprises, Club of Heroes, formerly White Lantern Corps, Sinestro Corps",
            "relatives": "Damian Wayne (son), Dick Grayson (adopted son), Tim Drake (adopted son), Jason Todd (adopted son), Cassandra Cain (adopted ward)\nMartha Wayne (mother, deceased), Thomas Wayne (father, deceased), Alfred Pennyworth (former guardian), Roderick Kane (grandfather, deceased), Elizabeth Kane (grandmother, deceased), Nathan Kane (uncle, deceased), Simon Hurt (ancestor), Wayne Family"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/639.jpg"
        }
    }, {
        "id": "71",
        "name": "Batman II",
        "powerstats": {
            "intelligence": "88",
            "strength": "11",
            "speed": "33",
            "durability": "28",
            "power": "36",
            "combat": "100"
        },
        "biography": {
            "full-name": "Dick Grayson",
            "alter-egos": "Nightwing, Robin",
            "aliases": ["Dick Grayson"],
            "place-of-birth": "-",
            "first-appearance": "-",
            "publisher": "Nightwing",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["5'10", "178 cm"],
            "weight": ["175 lb", "79 kg"],
            "eye-color": "Blue",
            "hair-color": "Black"
        },
        "work": {
            "occupation": "-",
            "base": "Gotham City; formerly Bludhaven, New York City"
        },
        "connections": {
            "group-affiliation": "Justice League Of America, Batman Family",
            "relatives": "John Grayson (father, deceased), Mary Grayson (mother, deceased), Bruce Wayne \/ Batman (adoptive father), Damian Wayne \/ Robin (foster brother), Jason Todd \/ Red Hood (adoptive brother), Tim Drake \/ Red Robin (adoptive brother), Cassandra Cain \/ Batgirl IV (adoptive sister)"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/1496.jpg"
        }
    }]
}

这是我的网络选项卡中的输出

在此处输入图像描述

标签: javascriptjsonreactjsreact-nativeaxios

解决方案


首先为什么要使用setLoading(true);下面的代码块它应该是false。正如你所说,装载机永远不会结束,那么我想你可能会进入 catch 块。

.catch(err => {
          setLoading(true);
          console.log(err.response);
        });

现在,如果这要捕获块,请使用静态 api 检查您的代码,因为目前在代码中看起来没有任何错误。

axios
        .get(`https://www.superheroapi.com/api.php/my-api-key/search/batman`)
        .then(res => {
          console.log("response= ", res);
        })
        .catch(err => {
          setLoading(true);
          console.log(err.response);
        });

如果它正常工作,则意味着您的查询有问题。


推荐阅读