简体   繁体   中英

How to validate url params with react-router?

I have a website that allows for urls of them form /widgets/:id . I have no more than 50 widgets, so /widgets/51 is not a valid url. How do I go about rendering an error page when id is bigger than 50?

Should I be validating the value of id in my Widget component? Or should I be validating it at the routes level? Also, I would prefer that the act of displaying an error page does not change the url. That is to say, if a user navigates to /widgets/51 I would like to display an error page, but I would like the url that gets displayed in the browser to keep reading /widgets/51 .

Many thanks in advance!

If you prefer that the URL doesn't not change when you handle the error message then, you should be having the logic to test the params in the Widget component. You should do it as follows

render() {
    if(this.props.match.params.id > 50) {
        return <ErrorView/>
    }else {
        return <WidgetView/>
    }
}

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