我在尝试更新项目时收到来自 redux 工具包的拒绝错误

IT技术 javascript reactjs arrays redux-toolkit
2022-07-20 01:02:00

我正在开发 MERN 应用程序,更新项目时遇到问题。我在发送补丁请求时遭到拒绝,并且没有太多信息可用于调试以解决问题。如果有人能指出我的代码中不正确的一些逻辑,我将不胜感激。先感谢您。下面是我实现的逻辑。

postService.js:

import axios from 'axios';

const API_URL = '/api/posts/';

const updatePost = async (postId, postData, token) => {
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };
  const response = await axios.patch(`${API_URL}/${postId}/`, postData, config);

  if (response.data) {
    return {
      ...response.data,
      id: postId,
    };
  }
};

postSlice.js:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import postService from './postService';

const initialState = {
  posts: [],
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: '',
};

export const updatePost = createAsyncThunk(
  'posts/updatePost',
  async (id, postData, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await postService.updatePost(id, postData, token);
    } catch (error) {
      const message =
        (error.response.data.message) ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

export const postSlice = createSlice({
  name: 'post',
  initialState,
  reducers: {
    reset: (state) => initialState,
  },
  extraReducers: (builder) => {
    builder
.addCase(updatePost.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(updatePost.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.posts = state.posts.map((post) =>
          post.id === action.payload.id ? action.payload : post
        );
      })
      .addCase(updatePost.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })
 });
  },
});

export const selectAllPosts = (state) => state.posts.posts;
export const { reset } = postSlice.actions;
export default postSlice.reducer;

表单.js:

const Form = ({ postId, setPostId }) => {
  const [formData, setFormData] = useState({
    postCreator: '',
    title: '',
    body: '',
    imageFile: '',
  });

  const dispatch = useDispatch();
  const user = JSON.parse(localStorage.getItem('user'));
  const post = useSelector((state) =>
    postId ? state.posts.posts.find((post) => post._id === postId) : null
  );

  useEffect(() => {
    if (post) setFormData(post);
  }, [post]);

  const clearPost = () => {
    setPostId(0);
    setFormData({
      postCreator: '',
      title: '',
      body: '',
      imageFile: '',
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (
      !formData.postCreator &&
      !formData.title &&
      !formData.body &&
      !formData.imageFile
    ) {
      toast.warning(
        'Please fill out all fields, and make sure you are also logged in'
      );
    } else if (postId) {
      dispatch(updatePost(postId, formData));
      console.log(postId);
    } else {
      dispatch(createPost(formData));
      clearPost();
      setPostId(null);
    }
    clearPost();
  };

在此处输入图像描述

1个回答

的第二个参数createAsyncThunkpayloadCreator. 的第一个参数payloadCreator是参数。的第二个参数payloadCreatorthunkAPI

因此,您应该将idand组合postData成一个对象来表示参数。

更新 postSlice.js:

export const updatePost = createAsyncThunk(
  'posts/updatePost',
  async ({id, postData}, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await postService.updatePost(id, postData, token);
    } catch (error) {
      const message =
        (error.response.data.message) ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

更新您发送 updatePost thunk 的位置:

updatePost({
  id: 123,
  postData: {
    foo: 'bar'
  }
})