2016-12-11 107 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

有這麼多的方法,你可以實現你想要的。當你剛開始做出反應的時候,你可能想要玩一下反應變化的狀態和道具。

您可以直接撥打axios獲取componentDidMount or componentWillMount中的方法,並將狀態保存在您的反應組件中。

隨着項目的發展,您可能想要嘗試更多的未來證明和易於維護的解決方案,如實施Redux。

0

如果你沒有使用任何框架(如Redux或Relay)componentDidMount是最好的選擇。 From react 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