我正在尝试使用OMDB API构建电影搜索应用程序。我的大多数应用程序都可以按需工作-除了搜索功能。每次我进行搜索时,结果都将显示为电影“未定义”(令人惊讶的是真实电影)。
Search result displays as the movie 'undefined'
有人知道为什么吗?我认为它与this.props.onSearch(e.target.value);
中的行handleSubmit
有关,但是我不确定在那里要更改什么。请原谅任何明显的错误-我是新手。
这是我的代码:
<!-----Search.js----->
import React from 'react';
import PropTypes from 'prop-types';
import Constants from 'expo-constants';
import MoviesList from './MoviesList';
class Search extends React.Component {
state = {
searchText: ''
}
onSearchChange = e => {
this.setState({
searchText: e.target.value
});
}
handleSubmit = e => {
e.preventDefault();
this.props.onSearch(e.target.value);
e.currentTarget.reset();
console.log(e.target.value);
// alert('search submitted!')
}
render() {
return(
<form className="search-form" onSubmit={this.handleSubmit}>
<input type="search"
onChange={this.onSearchChange}
name="search"
value={this.state.searchText}
placeholder="Search..." />
<button className="search-button" type="submit" id="submit">Go!</button>
</form>
);
}
}
export default Search;
<!------MoviesList.js----->
import React from 'react';
import Constants from 'expo-constants';
import PropTypes from 'prop-types';
import Search from './Search';
const MoviesList = props =>
<ul>
{props.results.map((result, index) =>
<li key={index}>
<b>{result.Title}</b> - <strong>{result.Year}</strong>
<p>{result.Plot}</p>
</li>
)}
</ul>
export default MoviesList;
<!----App.js----->
import React from 'react';
import {Button, SectionList, StyleSheet, Text, View, FlatList } from 'react-native';
import Constants from 'expo-constants';
import Search from './Search'
import MoviesList from './MoviesList'
const API_KEY = "xxxx";
export default class App extends React.Component {
constructor() {
super();
this.state = {
results: [],
isLoading: true,
movie: "tt3896198"
};
this.APIURL = `http://www.omdbapi.com/?page=3&t=${this.state.searchText}&apikey=${API_KEY}`;
}
searchMovies = (t = 'inception') => {
// alert('search movies!')
fetch(this.APIURL)
.then(response => response.json())
.then(data => {
const updateMovies = this.state.results;
updateMovies.push(data);
this.setState({
results: updateMovies,
})
})
.catch(error => {
console.log('Error fetching and parsing', error);
});
// console.log(this.state.results);
}
getMovies = async() => {
alert('get movies!')
fetch(`http://www.omdbapi.com/?&i=${
this.state.movie}&apikey=${API_KEY}`)
.then(resp => resp.json())
.then(data => {
console.log(data)
const importMovies = this.state.results;
importMovies.push(data);
this.setState({
results:importMovies,
})
});
}
componentWillMount() {
this.getMovies()
}
render() {
return (
<div className = "App">
<Search onSearch = {this.searchMovies} />
<div>
{
(this.state.loading) ? <p>Loading</p> :<MoviesList results={this.state.results} />
}
</div>
</div>
);
}
}