組件的數據來源,一般是經過Ajax請求從服務器獲取,能夠使用componentDidMount
方法設置Ajax請求,等到請求成功,再用this.setState
方法從新渲染UI。javascript
var UserGist = React.createClass({ getInitialState(){ return { username:'', lastGistUrl:'' }; }, componentDidMount(){ $.get(this.props.source,function(result){ var lastGist = result[0]; if(this.isMounted()){ this.SetState({ userName:lastGist.owner.login, lastGistUrl:lastGist.html_url }) } }.bind(this)); }, render(){ return ( <div> {this.state.username}'s last gist is <a href={this.state.lastGistUrl}>here</a>. </div> ) } }) ReactDOM.render( <UserGist source="https://api.github.com/users/octocat/gists" />, document.body )
上面代碼使用jQuery完成了Ajax請求,這是爲了便於說明。React自己沒有任何依賴,徹底能夠不用jQuery,而使用其餘庫。html
咱們甚至能夠把一個Promise對象傳入組件。java
ReactDOM.render( <RepoList promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} />, document.body )
上面代碼從Github的API抓取數據,而後將Promise對象做爲屬性,傳給RepoList
組件。react
若是Promise對象正在抓取數據(pending狀態),組件顯示「正在加載」;若是Promise對象報錯(rejected狀態),組件顯示報錯信息;若是Promise對象抓取數據成功(fulfilled狀態),組件顯示獲取的數據。git
var RepoList = React.createClass({ getInitialState: function() { return { loading: true, error: null, data: null}; }, componentDidMount() { this.props.promise.then( value => this.setState({loading: false, data: value}), error => this.setState({loading: false, error: error})); }, render: function() { if (this.state.loading) { return <span>Loading...</span>; } else if (this.state.error !== null) { return <span>Error: {this.state.error.message}</span>; } else { var repos = this.state.data.items; var repoList = repos.map(function (repo) { return ( <li> <a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description} </li> ); }); return ( <main> <h1>Most Popular JavaScript Projects in Github</h1> <ol>{repoList}</ol> </main> ); } } });