使用React进行授权和认证-路由器-DOM

时间:2018-12-14 15:03:03

标签: javascript reactjs react-router react-router-dom

你好,这是我第一次来这里。

在过去的几个小时中,我一直在努力解决此问题,但我无法理解该问题(我是新来的反应者)。

PrivateRoute中,我试图基于会话呈现身份验证组件。

  • session EXISTS =>身份验证组件应呈现
  • 不存在=>收到的组件应呈现

我得到的错误是:

Objects are not valid as a React child (found: [object Promise]). 
If you meant to render a collection of children, use an array instead.

我们将不胜感激!

这是我到目前为止所做的:

import Login from './Login'
import Register from './Register'
import React, {Component} from 'react'
import Authentication from './Authentication'
import { BrowserRouter , Redirect,  Route, Switch,} from 'react-router-dom'



const  Authorization= ()=>{
  return new Promise ((resolve,reject)=>{
    fetch('http://localhost:3000/content',{credentials:'include'}) //includes cookie from different port
    .then((res)=>res.json())
    .then((data)=>{
      if (data.user=="notLogged"){
        reject(false)
      }else    
        resolve(true)
    })
  })
}

const  PrivateRoute= async ({ component: Component})=> {
  var auth= await Authorization()
  console.log(auth);
  if (auth){
    return <Authentication/> 
  }else{
    return  <Component/>  
  }
}

class Index extends Component{
 
  render(){
    return(
      <BrowserRouter>
      {/* router may have only one child element- switch is the more common */}
        <Switch>
          <PrivateRoute exact path="/" component={Login}/>
          <PrivateRoute exact path="/login" component={Login} />
          <Route exact path="/register" component={Register} />
        </Switch>
      </BrowserRouter>
    )
  }
}

export default Index

1 个答案:

答案 0 :(得分:2)

找到了我的帖子的答案。

我一直做错了。

这是我到目前为止想出的

String.format()

工作正常!