我正在React / Redux应用程序中设置身份验证。保护路由之前,我使用Redux在本地存储中使用JWT令牌设置登录/注册/注销身份验证。现在,我正在尝试保护已登录用户的路由,并通过这篇出色的文章https://www.freecodecamp.org/news/how-to-protect-your-routes-with-react-context-717670c4713a/向我介绍了新的React Context API。
这是本文中使用简化的登录/注销方法的示例。
const AuthContext = React.createContext()
class AuthProvider extends React.Component {
state = { isAuth: false }
constructor() {
super()
this.login = this.login.bind(this)
this.logout = this.logout.bind(this)
}
login() {
setTimeout(() => this.setState({ isAuth: true }), 1000)
}
logout() {
this.setState({ isAuth: false })
}
render() {
return (
<AuthContext.Provider
value={{
isAuth: this.state.isAuth,
login: this.login,
logout: this.logout
}}
>
{this.props.children}
</AuthContext.Provider>
)
}
}
const AuthConsumer = AuthContext.Consumer
export { AuthProvider, AuthConsumer }
以下是来自redux的操作示例:
export const login_user = (data) => dispatch => {
dispatch({
type: LOGIN_INIT
})
fetch('http://localhost:8000/token-auth/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(json => {
localStorage.setItem('token', json.token)
dispatch(login_user_success(json.user))
})
.catch(error => {
dispatch(login_user_failure(error))
})
}
这是我的authReducer处理登录的情况:
...
case LOGIN_SUCCESS: {
return {...state, data: action.payload, logged_in: true}
}
...
已连接到Redux存储的原始LoginContainer.js:
...
const mapStateToProps = ({ user }) => ({
user_data: user.data,
logged_in: user.logged_in
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(AuthActions, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginContainer);
我尝试这样连接: AuthContext.js
...
const mapStateToProps = ({ user }) => ({
user_data: user.data,
logged_in: user.logged_in
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(AuthActions, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)({ AuthProvider, AuthConsumer })
但是在Nav组件中出现导入错误。