2017-04-06 67 views
0

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

我在做什么错?

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; 

回答

1

您使用的方式应该会引发错误,请检查console。您需要bind的上下文中使用回调方法里面this关键字您正在使用的.then,使用此:

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); 
     }); 
} 
+0

OMG谢谢,我忘了经典的'这个混乱'在JS :) – olefrank

1

您需要将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); 
      }); 
    } 
0
this 

内回调并不是指你的组件上下文,你需要爱可信的回调函数与反应成分结合该组件

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

的更新状态}