Reputation: 30335
I have some kind of a wizard where each step has it's own route. Now when a user uses a direct link to the second step route, I would like to redirect him to the first step (using browserHistory.replace).
The problem I face is that I don't really know which stage in the components life cycle it should be performed. I have tried constructor
, render
, componentWillMount
, but all of those do not prevent the component from rendering even if I use router. So what happens is that redirect occurs, but the component from the previous route still gets renders and fails (no data obviously).
Is there any "proper" way of redirecting during the component initialization (I need to check the state)? Or is there any other better way of doing so?
Upvotes: 1
Views: 1165
Reputation: 36827
In v2/3 you should use the onEnter
function to redirect (using the replace
function). v2/3 replicates most of React's life cycle functions because it doesn't really use React to render route components. That is to say, <Route>
s are just used for configuration and react-router
generates an array of components for a given route and renders each individually.
function redirectToStart(nextState, replace) {
if (!nextState.someCondition) {
replace('/initial-page')
}
}
<Route onEnter={redirectToStart} ... />
Upvotes: 1
Reputation: 30335
I don't know the "official" recommended way (still interested if someone can find it), but what worked for me is this:
componentWillMount
componentWillMount
to return null Example:
class MyComponent extends Component {
componentWillMount() {
if (!this.props.data) {
browserHistory.replace(myRoute);
}
}
render() {
if (this.props.data) {
return (
<div>
...
</div>
);
}
return null;
}
}
Upvotes: 1