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

时间:2016-10-26 11:36:26

标签: javascript reactjs axios

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

1 个答案:

答案 0 :(得分:8)

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

<强>解释

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