简体   繁体   English

如何在路由器转换过程中获取数据?

[英]How to fetch data during react router transition?

I want to fetch data every time a route is visited 我想在每次访问路由时获取数据

I tried to return something in my async function but i got a promise and i need just the value for rendering 我试图在我的异步函数中返回一些东西,但我得到了一个承诺,我只需要渲染的值

This is my fetch function i want to execute everytime a route is visited 这是我想要在每次访问路线时执行的获取功能

   isLogged = async()=>{
    //return 0;
    let response = await 
            fetch(`${CONFIG.server}/getStudentLogin`,{
        method: 'GET',
        headers: {
            'Authorization': 
                             store.getState().userDataLogged.token,
            'Content-Type': 'application/json'
        }
    })
    let dataResponse = await response.json();
    console.log(dataResponse)
    if(dataResponse.status == 500){
        //console.log("xd")
        return false;
    }
    return true;
}

And this is my render function for example 这是我的渲染功能

  <Route exact path="/student" render={()=>(
      this.isLogged() ? (
        this.isStudent() ? (                         
          <StudentView/>
        ):(
          <TeacherView/>
        )
      ):(
        <Redirect to="/login"/>
      )
   )}/>

The problem is isLogged function return me a promise but i need to return just a value, for example true or false 问题是isLogged函数给我一个承诺但我需要只返回一个值,例如true或false

In case you need to execute the promise you could simply add async before the function definition in render and then use await before the this.isLogged() 如果你需要执行promise,你可以简单地在render的函数定义之前添加async ,然后在this.isLogged()之前使用await

<Route exact path="/student" render={async ()=>(
      await this.isLogged() ? (
        this.isStudent() ? (                         
          <StudentView/>
        ):(
          <TeacherView/>
        )
      ):(
        <Redirect to="/login"/>
      )
   )}/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM