我有一個父組件,名爲UsersTable
(它是其他組件的子項,並具有users
和roles
作爲其道具)。 getRoles()
函數正在爲使用ajax請求的用戶獲取所有角色。結果返回到render()
並存儲在allroles
變量中。問題是因爲Ajax是異步的,我並不總是得到我需要的值在allroles
變量。它有時爲空或者爲所有用戶返回相同的值。我想我應該按照說明使用componentDidMount和componentWillReceiveProps。但我無法弄清楚。另外,我認爲allroles
應該是一個狀態,但這樣做會使代碼處於無限循環,並且瀏覽器會一直調用ajax請求!如何確保數據在渲染ReactJS組件之前已通過AJAX加載?
這裏是父組件代碼:
export const UsersTable = React.createClass({
getRoles(){
var oneRole = "";
this.props.users.forEach(function(user){
server.getUserRoles(user.id,
(results) => {
this.oneRole =results['hits']['hits']
notifications.success("Get was successful ");
},
() => {
notifications.danger("get failed ");
});
}.bind(this));
return this.oneRole;
},
render() {
var rows = [];
var allroles = this.getRoles()
this.props.users.map(function(user) {
rows.push(<UserRow userID={user.id}
userEmail={user.email}
userRoles={allroles}
roles={this.props.roles} />);
}.bind(this));
return (
<table className="table">
<thead>
<tr>
<th>Email Address</th>
<th>Role</th>
<th>Edit</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
});
這裏是子組件代碼:
export const UserRow = React.createClass({
var showRoles = this.props.userRoles.map((role) => <div> {role.description || ''}</div>);
render(){
return (
<tr>
<td>{this.props.userEmail}</td>
<td>{showRoles}</td>
</tr>
);
}
});
你不使用好AJAX asyncronous概念。 http://stackoverflow.com/questions/4559032/easy-to-understand-definition-of-asynchronous-event –