Как перенаправить LoginPage на HomePage после входа в систему - PullRequest
0 голосов
/ 02 апреля 2020

Я делаю проект с полным стеком с React в качестве внешнего интерфейса и flask в качестве внутреннего. Теперь я могу войти через веб-страницу React и установить User_status как активный в серверной части. Если пользователь вводит URL-адрес входа в браузер, я надеюсь, что он может перенаправить на домашнюю страницу.

Я пробовал несколько способов, но они не работают.

Первый способ: в маршрутизаторах. js

function check_active(){
      axios.get("http://localhost:5001/active_status").then(res => {
          console.log(res);
          return res.data.data.active_status
      }).catch(err => {
          console.log(err);
      });
}

const history = browserHistory;
const Routes=()=>(
    // check_active(),
    <Router history={browserHistory}>
        <Route path='/' component={Welcome}/>
        <Route path='register' component={Register}/>
        <Route path='login' component={Login}  render={props => (check_active() ? (<Redirect to='/'/>) : ( <Component {...props}/>))}/>
        <Route path='events' component={Events}/>
    </Router>
)

Затем я импортировал его в Index. js

ReactDOM.render(
  <Routes />,
  document.getElementById('root')
);

Второй способ: я создал privateRoute и импортировал его в Routes. js:

Вот здесь privateRoute. js:

class PrivateRoute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            active_status: true,
        };
    }

    componentDidMount() {
      axios.get("http://localhost:5001/active_status").then(res => {
          console.log(res);
          if(res.data.status==='success'){
            this.setState({'active_status':res.data.data.active_status})
          }
      }).catch(err => {
          console.log(err);
      });
  }

    render() {
        let { component: Component, ...rest} = this.props;
        if(this.state.active_status){
           return (
            <Route {...rest} render={(props) => ( <Component {...props} /> )}/>
            )
        }else{
          return (
            <Route {...rest} render={(props) => ( <Redirect to='/' /> )} />
            )
        }
    }
}

export default withRouter(PrivateRoute);

В маршрутах. js

const history = browserHistory;
const Routes=()=>(
    <Router history={browserHistory}>
        <Route path='/' component={Welcome}/>
        <PrivateRoute path='register' component={Register}/>
        <PrivateRoute path='login' component={Login}/>
        <Route path='events' component={Events}/>
    </Router>
)

Кто-нибудь знает, как это сделать?

...