2016-05-02 5 views
5

Attualmente sto usando "react-router": "^2.4.0" sulla mia applicazione di chat e ho confuso su come reindirizzare quando non ci sono utenti. Non penso che il reindirizzamento funzioni in "^2.4.0".Reindirizzare willTransitionTo in react-router 2.4.0?

Devo utilizzare i ganci onEnter sul mio percorso ?

Qualcosa di simile a questo:

<Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/> 

routes.js

<Route path="/" component={App} > 
    <IndexRoute component={Chat} /> 
    <Route path="chat" component={Chat} /> 
    <Route path="login" component={Login} /> 
</Route> 

Chat.jsx

static willTransitionTo(transition){ 
    var state = ChatStore.getState(); 
    if(!state.user){ 
    transition.redirect('/login'); 
    } 
} 

risposta

1

ho fatto funzionare utilizzando setRouteLeaveHook come si dice qui : https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

return false to prevent a transition w/o prompting the user

Tuttavia, dimenticano di menzionare che il gancio deve essere non registrato, vedere here e here.

Possiamo usare questo per implementare la nostra soluzione come segue:

class YourComponent extends Component { 
    constructor() { 
    super(); 

    const {route} = this.props; 
    const {router} = this.context; 

    this.unregisterLeaveHook = router.setRouteLeaveHook(
     route, 
     this.routerWillLeave.bind(this) 
    ); 
    } 

    componentWillUnmount() { 
    this.unregisterLeaveHook(); 
    } 

    routerWillLeave() { 
    // return false to prevent a transition w/o prompting the user, 
    // or return a string to allow the user to decide: 
    if (!this.state.isSaved) { 
     return 'Your work is not saved! Are you sure you want to leave?' 
    } 
    } 
    ... 
} 

YourComponent.contextTypes = { 
    router: routerShape 
};