[React] React Router: setRouteWillLeaveHook

setRouteWillLeaveHook provides a method for us to intercept a route change before leaving the current route.ide

 

Route Hook with Context to works with, So if we want to handle the route hook for Home Componet, we nee to add Context for Home Component:
class Home extends React.Component{

    componentWillMount(){
        this.context.router.setRouteLeaveHook(
            this.props.route,
            this.routeWillLeave
        )
    }

    routeWillLeave(nextLocation){
        console.log(nextLocation);
        return `Leave for next Location ${nextLocation.pathname}`;
    }

    render(){
        return <div><h1>Home</h1><Links></Links></div>
    }
}
Home.contextTypes = {
    router: React.PropTypes.object.isRequired
};

 

routeWillLeave is custom function, you can call it whatever you want, inside function, you can do the stuff you want, if you return a string, the string will show in alert dialog.ui

相關文章
相關標籤/搜索