【问题标题】:how to restrict access to the route如何限制对路由的访问
【发布时间】:2020-01-15 07:39:32
【问题描述】:

我的 App.js 中有

render() {
    return (
        <Router history={customHistory}>
            <div>
                    <Header/>
                    <Switch>
                    <Route exact path="/" component={HomePage}/>
                    <Route exact path="/test" component={ThankYou} />
                    <Route path="*" component={NotFound} status={404}/>
                    </Switch>
                    <Footer/>                        
            </div>
        </Router>
    );
}

这个溃败,我有联系表格added code to codpen for convenience

如何确保组件在路由上

&lt;Route exact path = "/test" component = {Test} /&gt;

只能在成功提交表单后进行,如果您尝试在其他时间进行,则重定向到 404

【问题讨论】:

    标签: reactjs forms redirect react-router submit


    【解决方案1】:

    一种通用的方法是创建PrivateRoute

    根据状态-formSubmitted,我们可以重定向到notFound或者404路由。

    class ProtectedRoute extends Component {
      render() {
        const { component: Component, ...props } = this.props
    
        return (
          <Route 
            {...props} 
            render={props => (
              this.state.formSubmitted ?
                <Component {...props} /> :
                <Redirect to='/notFound' />
            )}
          />
        )
      }
    }
    
    class AllRoutes extends Component {
      render() {
        return (
          <Switch>
            <Route path='/login' component={Login} />
            <ProtectedRoute path='/test' component={ThankYou} />
            <Route path="*" component={NotFound} />
          </Switch>
        )
      }
    }
    

    【讨论】:

    • 我理解正确,我在带有 app.js 的文件夹中创建了 ProtectedRoute 类(在其中我的路由),在其中我写了你写的内容并在 app.js 中导入,之后我写里面有一个新的 ProtectedRoute?
    • 我就是这样报错The above error occurred in the &lt;ProtectedRoute&gt;
    猜你喜欢
    • 2015-09-14
    • 2019-07-10
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2017-09-08
    • 2019-07-22
    • 2018-12-26
    • 2022-01-10
    相关资源
    最近更新 更多