Redux 登录状态判断的一些实践
最近一直在写一个React、Redux的前端项目,登录状态验证这一块还是比较头疼的。 我的实践下有三种方式来验证用户登录状态,目前我选择用三种方式一起用在项目里面。
之所以用三种方式一起是因为Redux高阶函数在性能调优的时候并不是特别容易。 Redux高阶函数验证//把需要登录状态验证的Component传入到这个高阶函数中 export function requireAuthentication(Component) { class AuthenticatedComponent extends Component { constructor(props) { super(props) } //只在首次Mount时来验证权限 componentWillMount() { this.checkAuth(); } checkAuth(){ const {path,isSignIn,dispatch}=this.props; if(!isSignIn){ //没有登录 //记录当前页面path //跳转到SignIn Page处理登录 登录完成够会跳回当前页面 dispatch(CommonActions.setNextUrl(path)) browserHistory.push('/sign'); } } render() { console.log('auth render') return ( <div> {this.props.isSignIn == true ? <Component {...this.props}/> : null } </div> ) } } const mapStateToProps = (state) => ({ path:state.routing.locationBeforeTransitions.pathname,isSignIn:state.common.isSignIn,state:state }) return connect(mapStateToProps)(AuthenticatedComponent); } 你可以把它像这样用在router中: { path:'courseCate',component:requireAuthentication(CourseCate)} 目前存在的一些问题:
Actions中间件验证export function checkAuth(nextUrl,nextFn) { return (dispatch,getState)=>{ //检测用户登录情况 if(!getState().common.isSignIn){ //没有登录 记录当前path //跳转到sign page 登录完成后 跳转回来 dispatch(setNextUrl(nextUrl)); pushUrl('/sign');//封装了 browserHistory.push(url) }else{ //通过验证后 执行下一个Fn dispatch(nextFn); } } } 你可以像这样用在你的Actions中 export function fetchFoo(url,conf) { return (dispatch,getState) => { if(shouldFetchFoo(getState())){ dispatch(requestFetchFoo()); return fetch(url,conf) .then(res=>res.json()) .then(json=>{ ... }) } } } export function needFetchFoo(nextUrl,url,conf){ retrun (dispatch)=>{ dispatch(checkAuth(nextUrl,fetchFoo(url,conf))) } } 目前存在的一些问题:
Component WillMount 验证这基本上可以认为是Actions中间验证的一种变种 export function checkAuthWithoutNextFn(nextUrl) { return (dispatch,getState)=>{ //check if user sign in if(!getState().common.isSignIn){ //if not set the nexturl //and push url to sign page dispatch(setNextUrl(nextUrl)); pushUrl('/sign'); } } } 你可以像这样把他用在Component WillMount事件中 componentWillMount(){ const {dispatch} = this.props; dispatch(CommonActions.checkAuthWithoutNextFn('/coursecate')); } 目前存在的一些问题:
举个例子: componentWillMount(){ const {dispatch} = this.props; dispatch(CommonActions.checkAuthWithoutNextFn('/coursecate')); } 然而子控件componentWillMount中有一个fetch是需要权限验证(此时父控件中并没有阻断子控件渲染,在父控件正在验证权限的同时,子控件的fetch执行了。高阶函数可以阻断子控件渲染)的。 总结1.高阶函数适合用在:子控件需要确定权限后渲染 大家雨露均沾 以上是我个人目前的一些小见解,欢迎各位指正和补充哈。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |