繁体   English   中英

获取数据后如何渲染页面

[英]How to render the page after fetching the data

我有以下 function 来检查用户

export const authCheckState = () => {
  return dispatch => {
    const token = localStorage.getItem("token");
    const email = localStorage.getItem("email");
    if (token === undefined) {
      dispatch(logout());
    } else {
      const expirationDate = new Date(localStorage.getItem("expirationDate"));
      if (expirationDate <= new Date()) {
        dispatch(logout());
      } else {
        dispatch(authSuccess(email, token));
        dispatch(
          checkAuthTimeout(
            (expirationDate.getTime() - new Date().getTime()) / 1000
          )
        );
      }
    }
  };
};

为此,我进行了特殊的初始化 function 它将获取所有需要的函数并调度它们

initialState = {
    initialized: false
};

const appReducer = (state = initialState, action) => {
    switch (action.type) {
        case INITIALIZED_SUCCESS:
            return {
                ...state,
                initialized: true
            }

        default:
            return state;
    }
}


export const initializedSuccess = () => ({type: INITIALIZED_SUCCESS});

export const initializeApp = () => (dispatch) => {
    let promise = dispatch(authCheckState());

    Promise.all([promise])
    .then(() => {
        dispatch(initializedSuccess());
    });
}

之后我将初始化 function 到应用程序的 componentDidMount function

componentDidMount() {
    this.props.initializeApp();
  }

在我这样做之后

const mapStateToProps = (state) => ({
  initialized: state.app.initialized
})

但在那之后我仍然太晚了,我必须刷新页面才能看到数据。 如何实现这个功能?

您应该在组件本身中获取数据。 使用 Redux 存储数据,以便您以后使用或操作它。 (如果你需要这样做!)

流程应该是这样的,

  1. 在 componentDidMount 上发出 API 请求。
  2. 将数据存储在 redux 中。
  3. 使用 Redux 在组件中以道具的形式使用该数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM