【问题标题】:Loading state before display new content显示新内容前的加载状态
【发布时间】:2021-07-10 17:28:47
【问题描述】:

我正在尝试使用 react 和 redux 实现乐观的 UI 加载。这是我的减速机:

const initState = {
  user: {},
  loading: true,
};

export default function (state = initState, action) {
  switch (action.type) {
   
    case GET_CURRENT_USER_BY_PROFILEID_LOADING:
      return {
        ...state,
        loading: true,
      };
    case GET_CURRENT_USER_BY_PROFILEID:
      return {
        ...state, 
        loading: false,
        user: action.payload.item,
      };

    default:
      return state;
  }
}

这是动作创建者:

export const getCurrentUserByProfileId = (profileId) => {
  return (dispatch) => {
    dispatch({ type: GET_CURRENT_USER_BY_PROFILEID_LOADING });
    baseUrl
      .get(
        Constants.RELATIVEPATH +
          Constants.USERS +
          '/' +
          profileId +
          Constants.PROFILEID,
        { headers }
      )
      .then((response) => {
        const data = response.data;
        dispatch({
          type: GET_CURRENT_USER_BY_PROFILEID,
          payload: { item: data },
        });
      })
      .catch((error) => {
        console.log(error);
        onError(error);
      });
  };
};

理想的情况是:Loading --> New state,我只在第一次加载时得到这个,之后是:Flash of old state --> Loading --> New state

【问题讨论】:

    标签: reactjs react-redux thunk optimistic-ui


    【解决方案1】:

    在向用户显示组件之前,您可以在不同的函数中调度 GET_CURRENT_USER_BY_PROFILEID_LOADING

    这样你就有了:

    1. 旧状态(未显示)
    2. GET_CURRENT_USER_BY_PROFILEID_LOADING
    3. 导航,或任何你做的显示组件
    4. 正在加载(显示)
    5. GET_CURRENT_USER_BY_PROFILEID
    6. 新状态(显示)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多