通过从redux存储中获取currentUser
,我授权了react路由器。
在页面之间进行切换没有问题,但是当刷新需要授权的页面时,由于currentUser
未定义,所以我无法对其进行授权。
componentDidMount
componentDidMount(){
this.props.actions.getCurrentUser()
}
路由器
<Route exact path="/profile/:id/settings" render={(props) => {
var urlId = props.match.params.id;
return this.props.isLogged ? this.props.currentUser.id == urlId ? < ProfileSettings {...props} /> : <Redirect to={"/profile/" + urlId} /> : <Redirect to="/" />;
}
} />
反应-redux
function mapDispatchToProps(dispatch) {
return {
actions: {
getCurrentUser: bindActionCreators(authAsyncActions.getCurrentUserApi, dispatch)
}
}
}
function mapStateToProps(state) {
return {
isLogged: state.isLoggedReducer,
currentUser: state.currentUserReducer
}
}
getCurrentUserApi
export function getCurrentUserApi() {
return async (dispatch, getState) => {
if (localStorageHelper.isExistsToken()) {
if (Object.keys(getState().currentUserReducer).length == 0) {
await axios.get(CURRENT_USER_PATH, {
headers: localStorageHelper.authHeaderObj()
}).then(res => {
dispatch(authActionsCreators.currentUserSuccess(res.data))
dispatch(authActionsCreators.isLoggedTSuccess())
}).catch(err => {
if (err.response.status === 401) {
var refreshToken = bindActionCreators(refreshTokenApi, dispatch)
refreshToken();
}
})
}
}
}
}