react登录认证

用 react 框架做项目时,如何实现登录认证呢?即登录成功加载当前页,否则跳转至登录页。可以写一个高阶函数来实现这个目的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { Component } from 'react'
import { connect } from 'react-redux'

export default function(ComposedComponent) {
class Auth extends Component {
componentWillMount() {
if (!this.props.auth.authorized) {
this.props.history.push('/login')
}
}

componentWillUpdate(nextProps) {
if (!nextProps.auth.authorized) {
this.props.history.push('/login')
}
}

render() {
return <ComposedComponent {...this.props} />
}
}

const mapStateToProps = state => ({
auth: state.auth
})

return connect(mapStateToProps)(Auth)
}

这里面用 redux 全局保存登录状态,定义了两个 action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const UNAUTH_USER = 'UNAUTH_USER'
export const AUTH_USER = 'AUTH_USER'

export function unauthUser() {
return {
type: UNAUTH_USER
}
}

export function authUser() {
return {
type: AUTH_USER
}
}

在 reducer 里面,初始化时从 localstorage 读取 token,如果有的话初试登录状态就是 true,否则为 false,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { AUTH_USER, UNAUTH_USER } from '../actions/authActions'
import storage from '../../shared/storage'

const token = storage.get('token')

const initialState = {
authorized: !!token // false
}

export default function (state = initialState, action) {
switch (action.type) {
case UNAUTH_USER:
return { authorized: false }
case AUTH_USER:
return { authorized: true }
default:
return state
}
}

如果想对某个组件进行登录认证,只需要把这个高阶函数作用于这个组件即可:

1
2
import Auth from '../../shared/components/Auth'
export default Auth(MyAwesomeComponent)