2016-10-26 4 views
4

React AJAX 예제에 따라 나는 영화를 가져 와서 렌더링하는 JSX 파일을 만들었다. 내가 아는 한, 나는 여기서 모든 것을하고있다. 난 내 렌더링 기능의 데이터를 CONSOLE.LOG 때React와 Axios가 두 번 발생 함 (한 번 정의되지 않았 으면, 성공적으로 한번)

나는이 개 결과를 얻을 :

  • 정의되지 않은
  • 개체 (내가해야 할 일이다, 그래서이 사람은 완벽하다)

내 렌더링 기능에서 if/else 로직을 수행하지 않고 어떻게 정의되지 않은 행을 필터링 할 수 있습니까? 결과를 반복하면 처음으로 오류가 발생하여 응용 프로그램이 중단됩니다.

이 문제를 해결하는 가장 좋은 방법은 무엇입니까?

편집 : 어쩌면 응용 프로그램은 Axios 호출이 완료되기 전에 렌더링됩니다. 어떤 경우에는 if/else 문을 사용해야합니까?

Heres는 내 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> 
) 
} 

답변

5

확인 렌더링 방법 내부 상태.

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.movie = []로 생성됩니다. 그런 다음 componentDidMount()가 트리거되어 상태가 변경됩니다. 이것은 렌더링 메소드를 다시 트리거합니다.

+1

기본적으로 소스에서 데이터를 가져 오기 전에 내 응용 프로그램이 렌더링되기 때문에 console.logged가 두 번 표시되는 이유는 무엇입니까? –

+1

상태가 변경 될 때마다 다시 렌더링이 트리거됩니다. 처음으로 Component는 this.state.movie = []로 생성됩니다. 그런 다음 componentDidMount()가 트리거되어 상태가 변경됩니다. 이것은 렌더링 메소드를 다시 트리거합니다. – dschu

+1

Gotcha! 위 코드를 추가하면 작동합니다. 저를 위해 그것을 해결해 주셔서 감사합니다 ;-) –

관련 문제