简体   繁体   中英

React router path validation and redirection

I'm using react-router with react-router-redux for implementation of SPA. I want to implement such a UI:

简单的用户界面架构

The main idea that I have a list of Entitnes and if I click on an Entity , url is changed from http://domain/entities to http://domain/entities/id , where id is an Entitiy 's id and the specific React component is loaded.

For performing navigation I'm using push method from react-router-redux but also I can just type a url path. But I need somehow validate url params. I want to check for id , is it in correct format and does the specific entity exist, and if not, I should rollback url to a previous state and then show an error alert.

I guess it is possible to do, but I'm a very beginner in React , so I would like to hear any advice from you.

Thanks in advance.

Learn about react-router hooks like onEnter , etc. You can determine them in your routes.

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

Example:

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>
);

Validation for login and router in ReactJs

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

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