2017-04-06 68 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> 
    ); 
} 

的更新狀態}