reactjs - 我正在尝试使用输入字段中的文本并按下搜索按钮进行 OMDB API 调用
问题描述
我的代码在这里:https ://github.com/justgoof9/IMDB/blob/master/src/App.js 这是我收到的错误:https ://i.imgur.com/9HK7egZ.png
在用户输入电影名称并按下搜索按钮后,谁能告诉我如何进行 API 调用?
解决方案
你非常接近——你只需要更新你正在调用的 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;
推荐阅读
- racket - 如何比较球拍中的数字和字符串
- python - 用pyenv安装anaconda,无法配置虚拟环境
- javascript - 一次上传数据框并在闪亮的应用程序中随处使用它
- types - Purescript 类型不统一
- twitter-bootstrap - 如何使用 Bootstrap for Drupal 在本地安装 Awesome Font?
- c# - 在 Visual Studio Code 中自动完成 switch-case
- numbers - 对于序列 1、1、2、2、4、2、6,序列中的下一项是什么?第n个词是什么?
- python - 尽管下载了 plotnine 包,但出现 No module named 'plotnine' 错误
- python - random.randint() 会生成随机数吗?我所有的猜测总是错的?
- r - 按 colname 标识填充矩阵