Я получаю данные внутри this.props.children; - PullRequest
0 голосов
/ 22 марта 2020

Я новичок в реакции, и у меня есть логин и эта функция, но мне нужно отправить информацию для следующей страницы о пользователе с this.props.children. Я надеюсь, что вы можете помочь мне, моя код в маршрутах следующий

<BrowserRouter>
        <Switch>
          <Route path="/" exact component={Carrousel} />
          <Route path="/registro" component={Register} exact/>
          <Route path="/login" component={Login} exact/>
          <Route path="/contact" component={Contact} exact/>
          <AuthComponent>
          <Route path="/protected" component={Protected} exact />
          </AuthComponent>
        </Switch>
      </BrowserRouter>

Мой код в authComponent для входа в систему

import React, {Component} from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
class AuhtComponent extends Component{
  constructor(props){
    super(props);

    this.state={
      user: undefined
    }
  }
  componentDidMount(){
   this.getUser();
  }
  getUser() {
    const jwt = getJwt();
    if (!jwt) {
      this.setState({
        user: null
      });
      return;
    }

    axios.get('getUser', { headers: { Authorization: `Bearer ${jwt}`} }).then(res => {
      this.setState({
        user: res.data
      })
    });
  }

  render(){
    const { user } = this.state;
    if (user === undefined) {
      return (
        <div>
          Loading...
        </div>
      );
    }

    if (user === null) {
      this.props.history.push('/login');
    }

    return this.props.children;
  }
}

export default withRouter(AuhtComponent);



И теперь я хочу восстановить информацию в защищенном компоненте nex, но я

import React, {Component} from 'react';

class Inicio extends Component{
  render(){
    return(
        <h1>{this.state.user}</h1>
    )
  }
}

Любая помощь приветствуется Ty

1 Ответ

1 голос
/ 02 апреля 2020

Вы должны использовать HO C (компоненты высшего порядка):

ссылка на рабочую версию:

https://codesandbox.io/s/busy-booth-hwllz

Код:

const withAuth = WrappedComponent =>
  class extends React.Component {
    constructor(props){
    super(props);

    this.state={
      user: undefined
    }
  }

  componentDidMount(){
   this.getUser();
  }

  getUser() {
    const jwt = getJwt();
    if (!jwt) {
      this.setState({
        user: null
      });
      return;
    }

    axios.get('getUser', { headers: { Authorization: `Bearer ${jwt}`} }).then(res => {
      this.setState({
        user: res.data
      })
    });
  }

  render(){
    const { user } = this.state;
    if (user === undefined) {
      return (
        <div>
          Loading...
        </div>
      );
    }

    if (user === null) {
      this.props.history.push('/login');
    }

    return <WrappedComponent {...this.props} user={user}/>;
  }
  };

export default withAuth;

и используйте его так:

<BrowserRouter>
        <Switch>
          <Route path="/" exact component={Carrousel} />
          <Route path="/registro" component={Register} exact/>
          <Route path="/login" component={Login} exact/>
          <Route path="/contact" component={Contact} exact/>
          <Route path="/protected" component={withAuth(Protected)} exact />
        </Switch>
</BrowserRouter>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...