Redux存储在页面刷新时未定义

时间:2020-10-04 16:24:34

标签: reactjs redux react-redux react-router

通过从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();
                    }
                })
            }
        }
    }
}

0 个答案:

没有答案