2016-12-11 2 views
1

방금 ​​react을 배우기 시작했습니다. 현재로서는 일부 응용 프로그램에서 일부 하드 코딩 된 데이터를 제공하고 있는데 일부 외부 API로 대체하여 그에 따라 데이터를로드하려고합니다. 지금까지 내가 한 일이 여기있다.reactjs에서 API 호출하기

import axios from "axios"; 
class TodoStore extends EventEmitter{ 
    constructor() { 
     super(); 
     this.todos = [ 
      { 
       id: 123, 
       text: "Go Shopping", 
       complete: false 
      }, 
      { 
       id: 456, 
       text: "Pay Bills", 
       complete: false 
      } 
     ]; 
    } 

getAll(){ 
     return this.todos; 
    } 

지금 내가하고 싶은 것을 내가 https://jsonplaceholder.typicode.com/todos를 구현하고 내 todos 모든 반환 된 결과를 할당 할 수 있습니다. 그렇다면 적절한 방법은 무엇입니까? 어떤 도움을 주시면 감사하겠습니다. 내가 말을해야

답변

0

제일 먼저 당신이 그 상태를 반응 사용하고 다음 react Life Cycle을 알아야하시기 바랍니다 있습니다 :

import axios from "axios"; 
class TodoStore extends EventEmitter{ 

      componentDidMount() { 

       axios.get('your url') 
       .then(function (response) { 
       this.setState({ 
        todos : response 
       }); 
       /// and you can get response with this.state.todos in your class 
       }) 
      .catch(function (error) { 
       console.log(error); 
      }); 

      } 


    } 
1

당신이 원하는 당신이 달성 할 수있는 많은 방법이 있습니다. 방금 반응을 시작 했으므로 변화하는 주와 소품에 반응하기를 원할 것입니다.

axioscomponentDidMount or componentWillMount에 직접 입력하고 반응 구성 요소에 상태를 저장할 수 있습니다.

프로젝트가 성장함에 따라 Redux를 구현하는 것과 같은 미래의 입증되고 유지 보수가 쉬운 솔루션을 시도 할 수 있습니다.

0

프레임 워크를 사용하지 않는 경우 (예 : Redux 또는 Relay) componentDidMount이 가장 적합한 곳입니다. 반응에서 Component Docs :

구성 요소가 마운트 된 직후 componentDidMount()가 호출됩니다. DOM 노드가 필요한 초기화는 여기에 있어야합니다. 원격 종점에서 데이터를로드해야하는 경우 네트워크 요청을 인스턴스화하는 데 좋습니다. 이 메소드의 상태를 설정하면 (자), 재 렌더링이 실행됩니다.

클래스는 다음과 같이 보일 것입니다 :

import axios from "axios"; 

class TodoStore extends EventEmitter{ 
    constructor() { 
     super(); 
     this.state = { todos: []} //initial todos - an empty array in state 
    } 

    componentDidMount() { 
     axios.get('https://jsonplaceholder.typicode.com/todos') 
     .then(function (data) { 
      this.setState({ 
       todos: data //set the received todos to state 
      }) 
     }) 
     .catch(function (error) { 
      console.log(error); 
     }); 
    } 

    getAll(){ 
     return this.state.todos; //get todos from state 
    } 
} 

더 많은 상태 : https://facebook.github.io/react/docs/state-and-lifecycle.html