[React Router v4] Intercept Route Changes

If a user has entered some input, or the current Route is in a “dirty” state and we want to confirm that data will be lost, React Router v4 provides a Prompt component to interrupt the Route transition and ask the user a question.

For example we need to way to tell user if he leaves the page, data will lost.

We can use 'Prompt' component from router lib. 

import React from 'react';
import {Link, Route, Prompt} from 'react-router-dom';

const Home = () => (<h1>Home</h1>);
class Form extends React.Component {
    state = {
        dirty: false
    };

    setDirty = () => {
        this.setState((preState, props) => {
            return {
                dirty: true
            }
        })
    };

    render(){
        return(
            <div>
                <h1>Form</h1>
                <input type="text" onInput={this.setDirty}/>
                <Prompt
                    when={this.state.dirty}
                    message="Date will be lost"
                ></Prompt>
            </div>
        );
    }
}



const Guards = () => (
    <div>
        <Link to="/guards/home">Home</Link>
        <Link to="/guards/form">Form</Link>

        <Route path="/guards/home" component={Home}></Route>
        <Route path="/guards/form"
               component={Form}
        ></Route>
    </div>
);

export default Guards;
原文地址:https://www.cnblogs.com/Answer1215/p/6603166.html