Javascript 在reactjs中调用api

Javascript 在reactjs中调用api,javascript,reactjs,Javascript,Reactjs,我刚刚开始学习react。到目前为止,我正在我的应用程序中输入一些硬编码数据,我希望用一些外部api替换这些数据,并相应地加载数据。以下是我到目前为止所做的 import axios from "axios"; class TodoStore extends EventEmitter{ constructor() { super(); this.todos = [ { id: 123,

我刚刚开始学习
react
。到目前为止,我正在我的应用程序中输入一些硬编码数据,我希望用一些外部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
并将所有返回的结果分配到my
TODO
。那么,正确的方法是什么呢?任何帮助都将不胜感激。

首先我要告诉您的是,请使用react state,然后您应该知道:


有很多方法可以实现你想要的。由于您刚刚开始使用react,您可能希望使用改变状态和道具的just react

您可以在
componentDidMount或componentWillMount
中直接调用
axios
get方法,并将状态保存在您的组件中


随着项目的发展,您可能希望尝试更多经得起未来考验且易于维护的解决方案,如实现Redux。

如果您不使用任何框架(如Redux或Relay)
componentDidMount
是最好的解决方案。从react:

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
    }
}
更多关于州的信息:

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
    }
}