我正在开发这个应用程序,它从电影API中获取数据,我想使用它。我有这个函数来获取API数据:
/** @format */
const fetchMovie = movie => {
var APIKEY = "xxxxxxxxxxxxxxxxxxxxxx";
var API2 =
"https://api.themoviedb.org/3/search/movie?api_key=xxxxxxxxxx&language=en-US&page=1&include_adult=false&query=avengers";
var API = `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&language=en-US&page=1&query=${movie}`;
fetch(API2)
.then(data => data.json())
.then(movies => console.log(movies) || movies.items)
.catch(error => {
console.log(error);
return null;
});
};
export default fetchMovie;我有一个使用API数据的App类:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
activeMovie: "Avengers",
loading: true,
allMovies: []
};
}
componentDidMount() {
this.getData(this.activeMovie);
}
componentDidUpdate(prevState) {
if (prevState.activeMovie !== this.state.activeMovie) {
this.getData(this.state.activeMovie);
}
}
getData(movie) {
this.setState({
loading: true
});
fetchMovie(movie).then(data => {
this.setState({
allMovies: data,
loading: false
});
});
}现在,在此之前,我已经使用了相同的方法,并且它起作用了,但是我不知道为什么I get TypeError: Object(...)(...)is undefined //此行数据(FetchMovie).then(data => {
API很好,我可以在数据到达App组件之前通过控制台记录数据,但app组件中的函数不知何故不起作用。有什么线索吗?
发布于 2020-01-27 02:26:39
这很简单,因为您的函数fetchMovie()没有返回Promise,因此您可以在它之后使用.then()。您可以返回一个promise。但是,代码中的逻辑可能有点不稳定。你也可以查一下,因为它进入了一个无限循环,考虑调试组件的生命周期。
要从您的函数返回promise,您可以使用类似于我在此处编写的方法:https://codesandbox.io/s/small-sun-sfcyv。
https://stackoverflow.com/questions/59920997
复制相似问题