基于api响应在路由组件上重定向-React Router

时间:2018-11-05 11:37:31

标签: reactjs react-router

每次加载根URL时,加载home组件时,都需要检查是否基于api设置了cookie。

<Route path="/" render ={() => {
  // checking the cookie exists
if(cookieExists){
  return (<HomePage />)
}else{
  axios.get("api/userLoggedIn")
     .then(res => {
          // the url is an external url [https://www.examplelogin.com]
          return(<div>Redirecting</div>
          {window.location.assign(res.data)}
          )
      })
      .catch(err => console.log("error in api", err))
}
}}
/>

我得到的错误是它-路线组件中的渲染未返回任何内容

1 个答案:

答案 0 :(得分:2)

您必须同步返回<div>Redirecting</div>

<Route path="/" render ={() => {
  // checking the cookie exists
if(cookieExists){
  return (<HomePage />)
}else{
  axios.get("api/userLoggedIn")
     .then(res => {
          // the url is an external url [https://www.examplelogin.com]
          window.location.assign(res.data);
      })
      .catch(err => console.log("error in api", err))
  return <div>Redirecting</div>;
}
}}
/>

axios调用是异步发生的,并且在重定向元素返回到路由器后,其响应得到处理。

相关问题