I am developing an application in which i check if the user is not loggedIn
I have to display the login form, else dispatch
an action
that would change the route and load other component. Here is my code:
render() {
if (isLoggedIn) {
// dispatch an action to change the route
}
// return login component
<Login />
}
How can i achieve this as i cannot change states inside render function.
In react-router version 4:
Another alternative is to handle this using Thunk-style asynchronous actions (which are safe/allowed to have side-effects).
If you use Thunk, you can inject the same
history
object into both your<Router>
component and Thunk actions usingthunk.withExtraArgument
, like this:Then in your action-creators, you will have a
history
instance that is safe to use with ReactRouter, so you can just trigger a regular Redux event if you're not logged in:Another advantage of this is that the url is easier to handle, now, so we can put redirect info on the query string, etc.
You can try still doing this check in your Render methods, but if it causes problems, you might consider doing it in
componentDidMount
, or elsewhere in the lifecycle (although also I understand the desire to stick with Stateless Functional Compeonents!)You can still use Redux and
mapDispatchToProps
to inject the action creator into your comptonent, so your component is still only loosely connected to Redux.Considering you are using
react-router v4
Use your component with
withRouter
and usehistory.push
from props to change the route. You need to make use ofwithRouter
only when your component is not receiving theRouter
props, this may happen in cases when your component is a nested child of a component rendered by the Router and you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes.or you could use Redirect
With
react-router v2 or react-router v3
, you can make use ofcontext
to dynamically change the route likeor use