W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
組件的數(shù)據(jù)來源,通常是通過 Ajax 請求從服務器獲取,可以使用 componentDidMount 方法設置 Ajax 請求,等到請求成功,再用 this.setState 方法重新渲染 UI (查看 demo11 )。
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.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: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
React.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.body
);
上面代碼使用 jQuery 完成 Ajax 請求,這是為了便于說明。React 沒有任何依賴,完全可以使用其他庫。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: