小编典典

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

reactjs

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

阅读 368

收藏
2020-07-22

共1个答案

小编典典

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

说明

每次状态更改时,都会触发重新渲染。第一次,您的组件是使用this.state.movi​​e =
[]构建的。之后,触发componentDidMount(),从而更改您的状态。这是第二次触发render方法。

2020-07-22