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

IT技术 javascript reactjs axios
2021-05-19 23:47:28

遵循 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个回答

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

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() 被触发,这会改变你的状态。这是第二次触发渲染方法。