本文介绍了React 和 Axios 触发两次(一次未定义,一次成功)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照 React AJAX 示例,我创建了一个 JSX 文件,其目的是获取和渲染电影.据我所知,我在这里做所有事情.

Following the React AJAX example i have created a JSX file which purpose is to fetch and render a movie.For all i know, i am doing everything right here.

当我在渲染函数中使用 console.log 记录数据时,我得到 2 个结果:

When i console.log the data in my render function i get 2 results:

  • 未定义
  • 对象(这是我需要的,所以这个是完美的)

如何在渲染函数中不做一些 if/else 逻辑的情况下过滤掉未定义的行?迭代结果当然会导致第一次出错,这会导致我的应用程序崩溃.

How can i filter out the Undefined row without doing some if/else logic in my render function?Iterating over the result will, of course, result in an error the first time, which will crash my application.

处理这个问题的最佳方法是什么?

What's the best way to handle this?

也许应用程序在 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>
  )
}

推荐答案

检查渲染方法内部的状态.通过这种方法,您可以渲染加载屏幕:

Check the state inside the render method. With this approach you can render a loading screen:

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

Every time the state changes, a re-render will be triggered. The first time, your Component is constructed with this.state.movie = []. After that, componentDidMount() is triggered, which changes your state. This is triggering the render method a second time.

这篇关于React 和 Axios 触发两次(一次未定义,一次成功)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:49
查看更多