首页 > 解决方案 > 如何在 React 中创建一个结构来防止一个动作在完成之前传递给另一个动作?

问题描述

当我发出 api 请求时,我将返回的数据保存在 redux 存储中,然后在路由中使用这些数据。

我想要做的是在将组件安装到路由之前对其进行授权,但由于路由中未定义数据,我无法授权。特别是当我刷新页面时,它变得未定义。

那么如何防止在加载之前currentUser渲染呢?Route

我应该如何解决这个问题?有解决问题的工具吗?

组件DidMount

componentDidMount(){
    this.props.actions.getCurrentUser()
  }

路由器 <Redirect to = "/" />重定向到这个,因为currentUser最初是未定义的

<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="/" />;
          }
   } />

反应还原

   function mapDispatchToProps(dispatch) {
      return {
        actions: {
          getCurrentUser: bindActionCreators(authAsyncActions.getCurrentUserApi, dispatch)
        }
      }
    }
  function mapStateToProps(state) {
      return {
        isLogged: state.isLoggedReducer,
        currentUser: state.currentUserReducer,
        isOwner: state.isOwnerReducer
      }
    }
 export default connect(mapStateToProps, mapDispatchToProps)(App);

获取当前用户接口

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

标签: reactjsreduxreact-reduxreact-router

解决方案


推荐阅读