Jeśli chcesz, że można napisać route.js tak:
var requireAuth = (store, nextState, replace) => {
console.log("store: ", store);
//now you have access to the store in the onEnter hook!
}
export default (store) => {
return (
<Route path="/" component={App}>
<IndexRoute component={Landing} />
<Route path="learn" component={Learn} />
<Route path="about" component={About} />
<Route path="downloads" component={Downloads} onEnter={requireAuth.bind(this, store)} />
</Route>
);
);
mam setup przykładem, który można grać w tym codepen.
Nie jestem pewien, czy wyzwalanie akcji w celu obsłużenia autoryzacji jest dobrym pomysłem. Osobiście wolę posługiwać się auth w w inny sposób:
Zamiast używać haczyka onEnter
, używam funkcji owijania. Chcę, aby sekcja administratora mojego bloga była chroniona, dlatego zawinąłem komponent AdminContainer
na trasach z funkcją, requireAuthentication
, patrz poniżej.
export default (store, history) => {
return (
<Router history={history}>
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={HomeContainer}/>
<Route path="post/:slug" component={PostPage}/>
{ /* <Route path="*" component={NotFound} status={404} /> */ }
</Route>
<Route path="/admin" component={requireAuthentication(AdminContainer)}>
<IndexRoute component={PostList}/>
<Route path=":slug/edit" component={PostEditor}/>
<Route path="add" component={PostEditor}/>
</Route>
<Route path="/login" component={Login}/>
</Router>
);
};
requireAuthentication
to funkcja
- jeśli użytkownik jest uwierzytelniony, renderuje owinięte komponentu
- inaczej przekierowuje do
Login
Można go zobaczyć poniżej:
export default function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount() {
this.checkAuth();
}
componentWillReceiveProps (nextProps) {
this.checkAuth();
}
checkAuth() {
if (!this.props.isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
this.context.router.replace({pathname: '/login', state: {redirectAfterLogin: redirectAfterLogin}});
}
}
render() {
return (
<div>
{this.props.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.blog.get('isAuthenticated')
});
AuthenticatedComponent.contextTypes = {
router: React.PropTypes.object.isRequired
};
return connect(mapStateToProps)(AuthenticatedComponent);
}
Ponadto, requireAuthentication
będzie chronić wszystkie trasy pod numerem /admin
. I możesz go użyć ponownie, gdziekolwiek chcesz.
ów wielki przykład. Wielkie dzięki :) – shivam
Jak by to działało z renderowaniem serwera? – Enkay
TY trochę, takie podejście jest naprawdę łatwe, ale muszę zapytać, czy jest jakaś remisja? – StormRage