简体   繁体   中英

ReactJs - redirect url

I am new to reactjs - and if I hit an error page on a subpage - because the url is wrong - I am looking to find a way to redirect the page to another.

So de/dienstleistungen/isdfisf -- spelt wrong redirect to de/dienstleistungen

I've tried to write a function to handle this but no luck

  if (!lang.serviceIntro[0][service]) {
    console.log('undefined', this)
    this.context.router.push('/de/dienstleistungen')
  }

Failed context type: Invalid context router of type object supplied to PlainHeader , expected function .

are you using react-router? and if used which version are you on it? Check out https://reacttraining.com/react-router/web/api/history which is currently on v4. This is my code

class App extends Component {
    componentDidMount() {
        let token = ... // achieve token
        if (!token) {
            this.props.history.push('/login');
        }
    }

    render() {
        ....
    }
}

my code in main page checking if not authenticated will redirect to login page programmatically. Props this.props.history will be passed by react router through . Check the docs above for more information. Hope it help

As the error message says, you should declare contextTypes.router as an object, router was a function in older versions

static contextTypes = {
  router: PropTypes.object.isRequired
}

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