React 和 Axios 触发两次(一次未定义,一次成功)

React and Axios fires twice (once undefined, once successfully)

按照 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>
  )
}

检查渲染方法中的状态。使用这种方法,您可以呈现加载屏幕:

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>
  )
}

说明

每次状态改变,都会触发重新渲染。第一次,您的组件是用 this.state.movie = [] 构造的。之后, componentDidMount() 被触发,这会改变你的状态。这是第二次触发渲染方法。