react-router路由中传入无效的参数,如何转到404?

<Router history={history}>
    <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path=":category" component={Category} />
        <Route path="*" component={NotFound} />
    </Route>
</ROuter>

比如传入了一个不存在的category,如何判断,并转到404模块?

阅读 4.4k
1 个回答

什么叫“不存在的category” ?

意思是代码已经进入了Category组件,但发现这个:category不符合条件?

如果是这样的话,那直接return那个Notfound视图好了,像这样:

render: function () {
    var category = findCategoy(this.props.params.category);
    if (!category) {
        return <NotFound />;
    }
    
    //你的正常代码
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题