简体   繁体   中英

When in the React component life cycle can I execute a route change?

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?

I don't know the "official" recommended way (still interested if someone can find it), but what worked for me is this:

  1. Redirect during componentWillMount
  2. During render use the same condition as in 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;
  }
}

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} ... />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM