2016-03-06 71 views
2

我試圖通過製作一個簡單的應用程序來學習反應,其中我試圖從服務器獲取json格式的數據,然後將其呈現給視圖。問題是我收到一個錯誤,它說this.state.data爲空。我該如何解決這個問題?的代碼:當從API獲取數據時,React - this.state爲空內部呈現

class App extends React.Component { 

    constructor() { 
    super(); 
    //Query data 
    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93') 
     .then(response => response.json()) 
     .then((data) => { 
     this.setState({ 
      data: data 
     }) 

     }) 
     .catch(err => console.error('Error ', err.toString())); 

    } 

    getInitialState() { 
    return { 
     data: {} 
    }; 
    } 

    render() { 

    return (
     <h1>{this.state.data}</h1> 
    ); 

    } 
} 

ReactDOM.render(<App/>, document.getElementById('app')); 

回答

4

當使用ES6類作爲成分,沒有getInitialState方法調用。
相反,在構造函數中設置實際實例的狀態。

class App extends React.Component { 

    constructor() { 
    super(); 

    this.state = { 
     data: {} 
    }; 

    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93') 
     .then(response => response.json()) 
     .then(data => this.setState({ data })) 
     .catch(err => console.error('Error ', err.toString())); 

    } 

    render() { 
    return <h1>{this.state.data}</h1>; 
    } 
} 

ReactDOM.render(<App/>, document.getElementById('app')); 
+0

FWIW React團隊建議在'ComponentDidMount'中創建AJAX調用:https://facebook.github.io/react/tips/initial-ajax.html。 –

+0

@RickRunyon你能指點我們的文章解釋爲什麼我們不應該獲取'componentWillMount'內的數據嗎?我對此很好奇。謝謝 – Andreyco

+2

我不一定說你不應該這樣做,而是將React團隊所提倡的作爲最佳實踐。最好的解釋似乎是'componentDidMount'適用於所有副作用代碼(AJAX/DOM操作/附加事件)。有關於它的一個較舊的帖子[這裏](http://stackoverflow.com/questions/27139366/why-do-the-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi)。 –