gpt4 book ai didi

javascript - React.js 在获取完成之前渲染

转载 作者:行者123 更新时间:2023-12-03 03:05:35 24 4
gpt4 key购买 nike

好吧,我有一个问题,我的应用程序在获取完成之前进入渲染,因此渲染错误

这是代码

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>

);
}
}

这里的问题是第二个 fetch/getUsers 需要第一个 fetch 提供的 session key 才能工作,否则会给出缺少 session 的错误。并且因为由于某种原因它没有获取此 session key ,所以它没有设置信息,因此渲染函数将进入 if 语句并渲染 MilltimeLogin 组件而不是其余部分。任何人都知道如何确保第一次获取全部完成,以便第二次获取 session key 。

编辑如果我重新加载页面一次它可以工作,但这不是我想要的

最佳答案

提取是异步的,您可以阅读 here因此,没有任何东西可以保证当第二次获取开始时,第一次获取就会结束。
也许 await 前缀可以帮助您(阅读 this 了解更多信息)希望这对您的研究有所帮助

关于javascript - React.js 在获取完成之前渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com