Reetch.js在fetch完成之前呈现

时间:2017-11-08 14:56:16

标签: javascript reactjs session fetch

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

这是代码

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提供工作,否则它会给出一个错误的错误会话。并且因为它由于某种原因没有得到这个会话密钥它不设置信息所以render函数将进入if语句并渲染MilltimeLogin组件而不是其余的。任何人都知道如何确保第一次获取完成所以第二次获取会话密钥。

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

1 个答案:

答案 0 :(得分:1)

Fetch是异步的,因为你可以阅读here,所以没有什么可以保证你第二次启动时第一次获取将结束。
也许await前缀可以帮助你(阅读this了解更多信息) 希望这可以帮助您进行研究

相关问题