首页 > 解决方案 > redux 发送响应和返回消息

问题描述

在我的操作中,我正在分派类型和有效负载,但如果我还希望将 res.status 和返回 JSON 消息包含到我的道具中怎么办。我将如何在我的 action 和 reducer 中这样做?

行动

export const fetchUserPosts = () => (dispatch) => {
  fetch(`${currentPort}/user/recipes`,
    {
      withCredentials: true,
      credentials: 'include',
    })
    .then((res) => {
      if (res.status !== 401) return res.json().then((data) => data);
      return { message: { msgBody: 'UnAuthorized' }, msgError: true };
    })
    .then((posts) => dispatch({
      type: FETCH_USER_POSTS,
      payload: posts,
    }));
};

减速器

export default function (state = initialState, action) {
  switch (action.type) {
    case FETCH_USER_POSTS:
      return {
        ...state,
        fetchUsersPosts: action.payload,
      };
    
    default:
      return state;
  }
}

标签: reactjsreduxreact-redux

解决方案


您可以将多个项目组合成一个有效负载。我会为成功和错误创建不同的操作。使用相同的操作会使 reducer 逻辑复杂化。使用 async/await 也比使用嵌套的 Promise 更容易。

这是一个使用SpaceX 开放 API的工作示例:

const FETCH_USER_POSTS_SUCCESS = 'FETCH_USER_POSTS_SUCCESS'
const FETCH_USER_POSTS_FAILED = 'FETCH_USER_POSTS_FAILURE'

const fetchPostSuccessAction = (payload) => ({
  type: 'FETCH_USER_POSTS_SUCCESS',
  payload,
})

const fetchPostFailureAction = (payload) => ({
  type: 'FETCH_USER_POSTS_FAILURE',
  payload,
})

const fetchUserPosts = () => async dispatch => {
  const res = await fetch('https://api.spacexdata.com/v3/launches/latest');
  
  if (res.status !== 401) {
    const { ships: posts } = await res.json();
    
    dispatch(fetchPostSuccessAction({
      posts,
      status: res.status,
    }))
  } else {
    dispatch(fetchPostFailureAction({ 
      message: { msgBody: 'UnAuthorized' },
    }))
  }
};

fetchUserPosts()(console.log)

reducer 可以通过解构对象来处理对象,并以您需要的任何方式将属性设置为新状态。您还可以更改其他属性,例如更改errMsgtruefalse根据操作的类型:

export default function (state = initialState, { type, payload }) {
  switch (type) {
    case FETCH_USER_POSTS_SUCCESS: {
      const { posts, status } = payload;
      
      return {
        ...state,
        status,
        fetchUsersPosts: posts,
        msgError: false,
        message: null
      };
    }
      
    case FETCH_USER_POSTS_FAILURE: {
      const { message } = payload;
      
      return {
        ...state,
        status: 401,
        fetchUsersPosts: null,
        msgError: true,
        message
      };
    }
    
    default:
      return state;
  }
}

推荐阅读