2016-05-02 10 views
5

Obecnie używam aplikacji "react-router": "^2.4.0" na mojej aplikacji do czatu i mam wątpliwości, w jaki sposób przekierować, gdy nie ma użytkownika. Nie sądzę, aby przekierowanie działa w "^2.4.0".Przekierowanie willTransitionTo w routerze reagującym 2.4.0?

Czy powinienem używać haczyków onEnter na mojej ścieżce chat?

coś takiego:

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

Odpowiedz

1

Zrobiłem to działa za pomocą setRouteLeaveHook jak mówi tutaj : https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

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

Jednak zapominają wspomnieć, że hak powinien być również niezarejestrowany, patrz here i here.

Możemy to wykorzystać, aby wdrożyć własne rozwiązanie w następujący sposób:

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