score:0

you should use component's lifecycle method componentdidupdate to handle route's updating as described in react-router-4 migration guide.

for example:

class appcontainer extends react.component {
  render() {
    return (
      <browserrouter>
        <div>
          <route path='*' component={rootroute}/>
        </div>
      </browserrouter>
    )
  }
}

class rootroute extends react.component {
  static proptypes = {
    history: proptypes.object, // this prop comes from withrouter feature
    location: proptypes.object, // this prop comes from withrouter feature
    user: proptypes.object // this prop should come from your app
  }

  componentdidupdate() {
    this.checksession({
      location: this.props.location.pathname,
      user: this.props.user
    })
  }

  checksession({location, user}) {
    if (!user.islogged() && !user.islocationpublic(location)) {
      this.props.history.push('/login')
    }
  }

  render() {
    return (
      <div>
        <switch>
          <route path='/login' component={loginroute}/>
          <route path='/backoffice' component={backofficeroute}/>
        </switch>
      </div>
    )
  }
}

export default withrouter(rootroute)

score:0

combining the two answers above, this worked for me:

  componentwillunmount() {
    const {location} = this.props;
    if(location.state && location.state.from) {
      this.props.history.push(location.state.from.pathname);
    } else {
      this.props.history.push('/');
    }
  }

don't do it in componentdidupdate - it will be called continuously.

score:4

since you are already passing the location from where you came as a location state to redirect in privateroute, you can use the same while redirecting back from login component

in the login component you would have

onsuccesslogin = () => {
   const {location} = this.props;
   if(location.state && location.state.from) {
      this.props.history.push(location.state.from);
   } else {
      this.props.history.push('/');
   }
}

Related Query

More Query from same tag