【问题标题】:React router path validation and redirectionReact 路由器路径验证和重定向
【发布时间】:2016-09-01 15:55:17
【问题描述】:

我正在使用 react-routerreact-router-redux 来实现 SPA。 我想实现这样的用户界面:

我有一个Entitnes 列表的主要思想,如果我点击Entityurlhttp://domain/entities 更改为http://domain/entities/id,其中idEntitiyid 并加载特定的 React 组件。

为了执行导航,我使用来自react-router-reduxpush 方法,但我也可以输入url 路径。 但我需要以某种方式验证url 参数。我想检查id,它的格式是否正确以及特定实体是否存在,如果不存在,我应该将url回滚到以前的状态,然后显示错误警报。

我想这是可能的,但我是React 的初学者,所以我想听听你的任何建议。

提前致谢。

【问题讨论】:

    标签: reactjs react-router react-router-redux


    【解决方案1】:

    了解 onEnter 等 react-router 钩子。您可以在路由中确定它们。

    https://github.com/ReactTraining/react-router/blob/v3/docs/Glossary.md#enterhook

    例子:

    var correctDataHandler = function(transition) {
        if( condition )
            transition.redirect('/')
    };
    
    var router = ReactDOM.render((
        <Router history={ReactRouter.createMemoryHistory()}>
            <Route path="/" component={ AddressForm } />
            <Route path="/map-page" component={ Map } onEnter={ correctDataHandler } />
            <Route path="/select-product-page" component={ CardsList } />
            <Route path="/login" component={ LoginRegisterPage } />
        </Router>
    );
    

    【讨论】:

    • 谢谢!正是我要找的!
    • 如何在onEnter中检查状态?想不通。
    • @vsync 这里是较新的文档(适用于 v3)https://github.com/ReactTraining/react-router/blob/v3/docs/Glossary.md#enterhook
    • 来自 react-router-v4 onEnter 和类似的属性已被删除。 Migrating from v2/v3 to v4
    【解决方案2】:

    在 ReactJs 中验证登录和路由器

    if(this.state.username==="admin" && this.state.password==="1234567")
                        {
                            this.props.history.push("/Welcome");
                        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      相关资源
      最近更新 更多