W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
在 componentDidMount
時加載數據。當加載成功,將數據存儲在 state 中,觸發(fā) render 來更新你的 UI。
當執(zhí)行同步請求的響應時,在更新 state 前, 一定要先通過 this.isMounted()
來檢測組件的狀態(tài)是否還是 mounted。
下面這個例子請求了一個 Github 用戶最近的 gist:
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" />, mountNode );
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: