如果你想,你可以寫route.js這樣的:
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>
);
);
我設置,你可以用這個codepen打一個比方。
不確定是否觸發操作以處理auth是個好主意。我個人更喜歡在以不同的方式處理身份驗證:
而不是使用onEnter
鉤子,我使用包裝功能。我希望我的博客的管理部分受到保護,因此我將AdminContainer
組件包裝在具有函數requireAuthentication
的路由中,如下所示。
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
是一個函數,
- 如果用戶進行身份驗證,使被包裝的成分,
- 否則重定向到
Login
您可以在下面看到它:
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);
}
此外,requireAuthentication
將保護/admin
下的所有路線。你可以在任何你喜歡的地方重複使用它。
這就是一個很好的例子。謝謝大家:) – shivam
這將如何與服務器渲染工作? – Enkay
TY有些多,這個方法真的很容易tom實現,但是我需要問一下,有沒有這個退縮? – StormRage