Mic*_*ijn 7 javascript reactjs axios
在React AJAX示例之后,我创建了一个JSX文件,其目的是获取和渲染电影.据我所知,我在这里做的一切.
当我在console.log中我的渲染函数中的数据得到2个结果:
如何在不使用渲染函数中的if/else逻辑的情况下过滤掉Undefined行?当然,迭代结果将导致第一次出错,这将导致我的应用程序崩溃.
处理这个问题的最佳方法是什么?
编辑:也许应用程序在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>
)
}
Run Code Online (Sandbox Code Playgroud)
检查render方法中的状态.使用此方法,您可以渲染加载屏幕:
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() {
//Loading...
if( this.state.movie[0] === undefined ) {
return <div>Loading...</div>
}
//Loaded successfully...
return(
<div> Movie loaded... [Do action here] </div>
)
}
Run Code Online (Sandbox Code Playgroud)
说明
每次状态改变时,都会触发重新渲染.第一次,您的Component使用this.state.movie = []构建.之后,触发componentDidMount(),这会改变您的状态.这是第二次触发渲染方法.
| 归档时间: |
|
| 查看次数: |
3362 次 |
| 最近记录: |