1

In my component I want to check if a user is logged and if not, then redirect to the login page. Currently I do the check and redirect in componentWillMount.

  public componentWillMount() {
    if(this.props.master === null) {
      this.props.history.push('./login');
    }
  }

However even though the redirect does occur both render() and componentDidMount() are still run, which crashes my code because in there I assume master is not null.

Eridanis
  • 410
  • 1
  • 6
  • 19

2 Answers2

1

Consider using a mechanism like this one:

When user is not logged in redirect to login. Reactjs

To redirect the user to the login page on the router, instead of the restricted component.

And please be careful with componentWillMount since it will be deprecated in future versions. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

rubentd
  • 1,245
  • 11
  • 25
  • 1
    Ahh, so you wrap your component inside another component, which decides to display it. Good solution, I will try it and if it works will mark this answer as accepted. It's a shame the react-router examples don't have any accompanying explanation. – Eridanis Oct 18 '18 at 13:27
  • Apologies for the late reply but this method worked well and the implementation is clean. – Eridanis Oct 22 '18 at 10:11
0

Try:

If shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked

shouldComponentUpdate() {
  if (this.props.master == null) return false
}

Answer originally from: Stop rendering of a component after componentDidMount()

Alexei Darmin
  • 2,079
  • 1
  • 18
  • 30