简体   繁体   English

如何使用react-router验证url参数?

[英]How to validate url params with react-router?

I have a website that allows for urls of them form /widgets/:id . 我有一个网站,允许他们使用/widgets/:id形式的网址。 I have no more than 50 widgets, so /widgets/51 is not a valid url. 我的窗口小部件不超过50个,因此/widgets/51不是有效的网址。 How do I go about rendering an error page when id is bigger than 50? id大于50时如何呈现错误页面?

Should I be validating the value of id in my Widget component? 我应该在我的Widget组件中验证id的值吗? 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. 另外,我希望显示错误页面的行为不会更改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 . 也就是说,如果用户导航到/widgets/51我想显示一个错误页面,但是我希望浏览器中显示的URL继续读取/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. 如果您希望处理错误消息时URL不变,那么您应该具有测试Widget组件中的参数的逻辑。 You should do it as follows 您应该按照以下步骤进行操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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