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