遵循 React AJAX 示例,我创建了一个 JSX 文件,其目的是获取和渲染电影。据我所知,我在这里做所有事情。
当我 console.log 渲染函数中的数据时,我得到 2 个结果:
- 不明确的
- 对象(这是我需要的,所以这个是完美的)
如何在渲染函数中不做一些 if/else 逻辑的情况下过滤掉未定义的行?迭代结果当然会在第一次导致错误,这会使我的应用程序崩溃。
处理这个问题的最佳方法是什么?
编辑:也许应用程序在 Axios 调用完成之前就被渲染了,在这种情况下我被迫做一个 if/else 语句?
这是我的 JSX 文件:
import React from "react";
import axios from "axios";
export default class NetflixHero extends React.Component {
constructor() {
super();
this.state = {
movie: []
}
}
}
componentDidMount() {
const apiKey = '87dfa1c669eea853da609d4968d294be';
let requestUrl = 'https://api.themoviedb.org/3/' + this.props.apiAction + '&api_key=' + apiKey;
axios.get(requestUrl).then(response => {
this.setState({movie: response.data.results})
});
}
render() {
//Fires twice. Returns Undefined and an Object
console.log(this.state.movie[0]);
return(
<div></div>
)
}