React.js 在获取完成之前渲染
React.js render before fetch is done
好的,我有一个问题,我的应用程序在完成提取之前进入渲染,因此呈现错误
这是代码
componentWillMount() {
fetch('http://localhost:8081/milltime/login?users='+this.state.email, {
})
fetch("http://localhost:8081/milltime/getUsers")
.then(res => res.json())
.then(info => {
this.setInfo(info);
for (var i = 0; i < info['mta:getUsersResponse']['mta:users'].length; i++) {
const user = {
id: info['mta:getUsersResponse']['mta:users'][i]['mta:UserId'],
username: info['mta:getUsersResponse']['mta:users'][i]['mta:UserLogin'],
name: info['mta:getUsersResponse']['mta:users'][i]['mta:FullName']
}
this.addUser(user);
}
}).then(function() {
console.log("signed in to milltimes");
}).catch(function() {
console.log("need to sign in to milltime");
});
}
setInfo(info) {
this.setState({
info: info,
})
}
render() {
if (!this.state.info) {
return (
<MilltimeLogin email={this.state.email}/>
);
}
return(
<div className="usersTable">
<Table striped bordered condensed responsive hover>
<thead>
<tr>
<th/>
<th className="title">Employees</th>
<th/>
</tr>
<tr>
<th>Id</th>
<th>Full Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{
Object
.keys(this.state.Users)
.map(key => <User key={key} index={key} details={this.state.Users[key]} onChange={this.props.onChange} />)
}
</tbody>
</Table>
</div>
);
}
}
这里的问题是第二次获取 /getUsers 需要第一次获取提供的会话密钥才能工作,否则它会给出一个错误,指出它缺少会话。并且由于某种原因它没有获得此会话密钥,因此它没有设置信息,因此呈现函数将进入 if 语句并呈现 MilltimeLogin 组件而不是其余部分。任何人都知道如何确保第一次获取全部完成,以便第二次获取会话密钥。
编辑,如果我重新加载页面一次它可以工作,但那不是我想要的
好的,我有一个问题,我的应用程序在完成提取之前进入渲染,因此呈现错误
这是代码
componentWillMount() {
fetch('http://localhost:8081/milltime/login?users='+this.state.email, {
})
fetch("http://localhost:8081/milltime/getUsers")
.then(res => res.json())
.then(info => {
this.setInfo(info);
for (var i = 0; i < info['mta:getUsersResponse']['mta:users'].length; i++) {
const user = {
id: info['mta:getUsersResponse']['mta:users'][i]['mta:UserId'],
username: info['mta:getUsersResponse']['mta:users'][i]['mta:UserLogin'],
name: info['mta:getUsersResponse']['mta:users'][i]['mta:FullName']
}
this.addUser(user);
}
}).then(function() {
console.log("signed in to milltimes");
}).catch(function() {
console.log("need to sign in to milltime");
});
}
setInfo(info) {
this.setState({
info: info,
})
}
render() {
if (!this.state.info) {
return (
<MilltimeLogin email={this.state.email}/>
);
}
return(
<div className="usersTable">
<Table striped bordered condensed responsive hover>
<thead>
<tr>
<th/>
<th className="title">Employees</th>
<th/>
</tr>
<tr>
<th>Id</th>
<th>Full Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{
Object
.keys(this.state.Users)
.map(key => <User key={key} index={key} details={this.state.Users[key]} onChange={this.props.onChange} />)
}
</tbody>
</Table>
</div>
);
}
}
这里的问题是第二次获取 /getUsers 需要第一次获取提供的会话密钥才能工作,否则它会给出一个错误,指出它缺少会话。并且由于某种原因它没有获得此会话密钥,因此它没有设置信息,因此呈现函数将进入 if 语句并呈现 MilltimeLogin 组件而不是其余部分。任何人都知道如何确保第一次获取全部完成,以便第二次获取会话密钥。
编辑,如果我重新加载页面一次它可以工作,但那不是我想要的