成功 AJAX 请求后未更新的状态



我正在做一个基本的React应用程序,其中包含来自我的api的数据。但是当我在 AJAX 成功后this.setState({})时,状态不会更新。状态事件在render方法中为空。

我做错了什么?

import React, {PropTypes, Component} from 'react';
import axios from 'axios';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            events: []
        };
    }
    componentDidMount() {
        axios.get('http://localhost:4000/api/v1/events')
            .then(function (response) {
                this.setState({events: response.data});
            })
            .catch(function (error) {
                console.warn(error);
            });
    }
    render() {    
        // this.state.events keeps being an empty array []
        return (
            <div className="home">
              {
                this.state.events.map((month) => {
                  console.log(month) 
                })
              }
            </div>
        );
    }
}
export default App;

您使用的方式应该抛出错误,请检查console。你需要bind上下文才能在.then中使用的回调方法里面使用this关键字,使用这个:

componentDidMount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then( response => {
            console.log('data', response.data);
            this.setState({events: response.data});
        })
        .catch(function (error) {
            console.warn(error);
        });
}

或者使用 .bind(this) 绑定上下文,如下所示:

componentDidMount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then(function (response) {
            this.setState({events: response.data});
        }.bind(this))
        .catch(function (error) {
            console.warn(error);
        });
}

您需要将 axios 成功函数绑定到正确的上下文中才能使用 setState。使用这个

componentDidMount() {
        axios.get('http://localhost:4000/api/v1/events')
            .then(function (response) {
                this.setState({events: response.data});
            },bind(this))
            .catch(function (error) {
                console.warn(error);
            });
    }
this

内部回调不引用您的组件上下文,因为您需要将 axios 的回调函数与 react 组件绑定以更新该组件的状态

import React, {PropTypes, Component} from 'react';
import axios from 'axios';
import './App.css';

class App extends Component {
constructor(props) {
    super(props);
    this.state = {
        events: []
    };
}
componentDidMount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then(function (response) {
            this.setState({events: response.data});
        }.bind(this)) // binding of callback to component
        .catch(function (error) {
            console.warn(error);
        });
}
render() {    
    // this.state.events keeps being an empty array []
    return (
        <div className="home">
          {
            this.state.events.map((month) => {
              console.log(month) 
            })
          }
        </div>
    );
}

}

最新更新