Авторизация и аутентификация с использованием реакции - роутер - dom

1

Здравствуйте, это мой первый раз здесь.

Я пытался решить эту проблему в течение последних нескольких часов, и я не могу понять проблему (я новичок, чтобы реагировать).

В PrivateRoute я пытаюсь визуализировать компонент аутентификации на основе сеанса.

  • сеанс EXISTS => Компонент аутентификации должен отображать
  • NOT 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
  • 0
    Эта ошибка возникает независимо от ответа для var auth= await Authorization() ?
  • 0
    Нет, это генерируется в этой строке, у меня были некоторые трудности с возвратом результата авторизации, поэтому я попробовал это с помощью Promises. и ошибка согласна.
Теги:
react-router
jsx
react-router-dom

1 ответ

1

Нашел ответ на мой пост.

Я делал это неправильно.

Это то, что я придумал до сих пор

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


 const PrivvatRoute=({ component: Component, user})=>(
  <Route  render={(props) =>  user==="notLogged" ?  <Component/> : <Authentication user={user} /> } />
)

class Index extends Component{
  constructor(props){
    super(props);
    this.state={user:""}
}
 
render(){
 return(
 <BrowserRouter>
 {/* router may have only one child element- switch is the more common */}
    <Switch>
       <PrivvatRoute exact path="/"   component={Login} user={this.state.user}   />
       <PrivvatRoute exact path="/login"   component={Login} user={this.state.user} />
       <PrivvatRoute exact path="/register"  component={Register} user={this.state.user}  />
    </Switch>
  </BrowserRouter>
)
}


componentWillMount(){
  fetch('http://localhost:3000/content',{credentials:"include"})
  .then((data)=>data.json())
  .then((data)=>{this.setState(data);  console.log(data)
 
 })
 }
}

export default Index

и работает отлично!

  • 0
    Мне нравится видеть, как люди отвечают на свои вопросы. отлично сработано.
  • 0
    Спасибо, мужик !

Ещё вопросы

Сообщество Overcoder
Наверх
Меню