首页 > 解决方案 > 我正在尝试使用输入字段中的文本并按下搜索按钮进行 OMDB API 调用

问题描述

我的代码在这里:https ://github.com/justgoof9/IMDB/blob/master/src/App.js 这是我收到的错误:https ://i.imgur.com/9HK7egZ.png

在用户输入电影名称并按下搜索按钮后,谁能告诉我如何进行 API 调用?

标签: reactjs

解决方案


你非常接近——你只需要更新你正在调用的 API url。具体来说,您没有在您的州设置电影 ID,因此您的 api 调用如下所示:http ://www.omdbapi.com/?i=&apikey=480344f1 。如果您在浏览器中跟踪该 url,您会看到它返回您正在记录的错误消息。如果您指定电影 id(例如 tt3896198),您会看到您得到正确的 API 响应http://www.omdbapi.com/?i=tt3896198&apikey=480344f1

我更新了下面的代码片段以在组件的状态下设置初始电影 ID:

import React, { Component } from "react";
import { Input } from "antd";
import "./App.css";
import { Button } from "antd";

const API_KEY = "480344f1";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      movie:"tt3896198",
      movies: []
    };
    this.APIURL = `http://www.omdbapi.com/?i=${
      this.state.movie
    }&apikey=${API_KEY}`;
  }

  changeUserInput = movie => {
    this.setState({ movie });
  };

  onSubmit= (movie) => {
   this.componentWillMount();
  }

  componentWillMount() {
    fetch(this.APIURL)
      .then(resp => resp.json())
      .then(data => {
        console.log(data)
        const updatedMovies = this.state.movies;
        updatedMovies.push(data);
        this.setState({
          movies:updatedMovies,
        })
        console.log(this.state.movies);
      });
  }

  render() {
    return <div>
        <br />
        <br />

        <Input placeholder="Basic usage" placeholder="Search Movies" onChange={e => this.changeUserInput(e.target.value)} />
        <Button
        type="primary"
        shape="circle"
        icon="search"
        onClick={() => this.onSubmit()} />
      </div>;
  }
}

export default App;

推荐阅读