1
I’m doing an application in React and I want to make a check, if the guy is authenticated, redirect directly to Home, if not, goes to the Login screen, this is the Code:
userReducer.js
const initialState = {
isAuth: false
}
rootReducers.js
export default combineReducers({
login: loginReducer,
user: userReducer
})
App.js
function App(props) {
let { isAuth } = props;
return (
<div className="App">
<Root
isAuth={isAuth}
/>
</div>
);
}
function mapStateToProps(state) {
return {
isAuth: state.user.isAuth
};
}
export default connect(mapStateToProps)(App);
root js.
class Root extends Component {
constructor(props){
super(props);
}
componentDidMount() {
if(!this.props.isAuth) {
return <Redirect to="/Login" />
}
}
render() {
return (
<BrowserRouter>
{
window.location.pathname === '/Login' ? ''
:
<Navbar
logo={ logo }
background="#fff"
hoverBackground="#ddd"
linkColor="#777"
/>
}
<Switch>
<Route path="/Login" exact component={Login} />
<Route path="/Home" component={Home} />
<Route path="/Treinos" component={Treinos} />
<Route path="/Lives" component={Lives} />
<Route path="/Video_Aulas" component={VideoAulas} />
<Route path="/" exact component={Home} />
</Switch>
</BrowserRouter>
);
}
}
export default Root;
So in the store
i have a variable isAuth
, I get it in my App.js and step as prop
for my root js., I want when mine root js. initiate it to check whether or not it is authenticated, thing it is already doing, but if it is not if(!this.props.isAuth){...}
redirect to '/Login'
.
But the variable arrives at it as false
, he identifies that is to enter the if
but nothing happens. Why does my Redirect not work? Is it a conflict with Redux or something? How to solve?
Pow, it worked fine, thank you very much man! I’m a little new still in React, I came from Angular, so some things are very confusing, but thank you very much!
– Ban