如何在React中使用该操作调用中的某些消息还原Redux操作调用

时间:2020-10-22 18:56:44

标签: reactjs redux action redux-thunk

首先,我是redux的新手。我正在尝试使用reduxjsonPlaceholderAPI创建一个CRUD react应用程序。我正在使用redux-thunk作为redux中间件。在我的fetchResources操作中,我正在调用GET api,并将响应发送给reducer以更新商店。但是我的问题是,当API调用由于任何系统错误而失败时,如何发送一些错误消息。为了更好地理解,here是我在codesandbox中准备好并准备好的项目的链接。如果我不清楚自己的意思,我想知道操作调用失败时的过程以及如何通过向用户发送一些消息来处理它。我在下面添加了我项目的核心代码段。

操作

import jsonPlaceholder from '../apis/jsonPlaceholder';
import _ from 'lodash';

export const fetchPosts = () => async(dispatch)=>{
    let {data} = await jsonPlaceholder.get('/posts');
    data = _.drop(data, 95);
    dispatch({type: 'FETCH_POSTS', payload:data});
};

export const createPost = ({title, body}) => async dispatch=>{
    let {data}  = await jsonPlaceholder.post('/posts',{title, body, userId:_.random(1,10)});
    dispatch({type:'CREATE_POST', payload:data});
};

export const updatePost = (post) => async dispatch=>{
    let {data}  = await jsonPlaceholder.put(`/posts/${post.id}`,post);
    dispatch({type:'UPDATE_POST', payload:data});
};

export const deletePost = (postId) => async dispatch=>{
    await jsonPlaceholder.delete(`/posts/${postId}`);
    dispatch({type:'DELETE_POST', payload:postId});
};

减速器

export default (state = [], action) => {
switch (action.type) {
  case "FETCH_POSTS":
    return action.payload;
  case "CREATE_POST":
    return [...state, action.payload];
  case "UPDATE_POST":
    return state.map((post) =>
      post.id === action.payload.id ? action.payload : post
    );
  case "DELETE_POST":
    return state.filter((post) => post.id !== action.payload);
  default:
    return state;
}
};

/***Index Reducer***/
import {combineReducers} from 'redux';
import postReducers from '../reducers/postReducers';

export default combineReducers({
    posts: postReducers
});

主要组件

import React, { useEffect } from "react";
import Post from "./Post";
import { connect } from "react-redux";
import { fetchPosts } from "../../actions";

const PostList = ({ posts, fetchPosts }) => {
  useEffect(() => {
    fetchPosts();
  }, []);
  const list = posts.map((post) => <Post key={post.id} post={post} />);
  return <>{list}</>;
};

const mapStateToProps = (state) => {
  return {
    posts: state.posts
  };
};
export default connect(mapStateToProps, { fetchPosts })(PostList);

1 个答案:

答案 0 :(得分:0)

  1. 如果您的API调用返回并出错,则可以验证您的响应是否包含错误或某些错误状态,并调度错误操作:

    export const updatePost =(post)=>异步调度=> {

        const response  = await jsonPlaceholder.put(`/posts/${post.id}`,post);
        if(response.status !== 200 || response.error (*for example)) {
         dispatch({type:'ERROR', payload:response.error});
    
    
    } else {
             dispatch({type:'UPDATE_POST', payload:response.data});
    
      }
         };
    

您还可以为其创建一些包装器。

  1. Axios为您提供拦截器 https://github.com/axios/axios#interceptors

您可以使用它,并在出现某些响应错误时使错误处理失效