I
I
Incold2020-05-28 15:35:58
React
Incold, 2020-05-28 15:35:58

Why doesn't Redirect react-router-dom work?

Hello! Faced a small problem.

import React, {useState, useEffect} from 'react';
import Navbar from './Navbar';
import {connect} from 'react-redux';
import Auth from './Auth';
import MainPage from './MainPage';
import { CSSTransition } from 'react-transition-group';
import {Route, Redirect, Switch, withRouter} from 'react-router-dom';

function App(props) {

  const [animation, showAnimation] = useState(false);

  useEffect(() => {
    showAnimation(true);
  })
  console.log(props.isLogin); // выводит правильно 
  return (
    <div className="d-flex flex-column flex-fill h-100">
      <Navbar />

      <Switch>
        <Route path='/auth' render={() =>
          <CSSTransition
            in={animation}
            timeout={500}
            classNames="login"
            unmountOnExit
          >
            <Auth />
          </CSSTransition>
        } />
        <Route path='/main' component={MainPage} />
        {props.isLogin ? <Redirect to="/main" /> : <Redirect to="/auth" />}
      </Switch>

    </div>
  );
}

export default withRouter(connect(
  state => ({
    isLogin: state.login.isLogin
  }),
  null
)(App));


Perhaps I'm just using Route and Redirect incorrectly, but I want to make sure that when isLogin changes, it redirects me to the main page, isLogin changes but the url does not change, so the main page is not displayed. How to fix it?

Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-05-28
@Incold

it will only redirect you if you are not on / main or / auth, otherwise the first two Routes in Switch will work and Redirect will simply not reach.
you can add a props.isLogin check to each Route
{props.isLogin && }
{!props.isLogin && }
but that's not accurate
https://reacttraining.com/react-router/web/example... see more as an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question