首页 > 解决方案 > react/redux app post请求添加数据库不起作用

问题描述

我正在使用 redux 工具包创建一个 react/redux 应用程序并尝试将数据添加到后端 vis node/mongodb api,我正在尝试添加 create 函数并将一些帖子保存到 db 中,它保存在 redux 但不保存在 mongodb数据库不知道为什么会发生,如果有人知道请检查

下面是我的 redux 切片文件

import {
  createSlice,
  // createSelector,
  // PayloadAction,
  createAsyncThunk,
} from "@reduxjs/toolkit";
import axios from "axios";

// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched. Thunks are
// typically used to make async requests.

//http://localhost:5000/posts/

export const fetchAllPostsAsync = createAsyncThunk(
  "posts/fetchAllPostsAsync",
  async (_, thunkAPI) => {
    try {
      const response = await axios.get("http://localhost:5000/posts/");
      return response.data;
    } catch (error) {
      throw thunkAPI.rejectWithValue({ error: error.message });
    }
  }
);

export const postsingleAsync = createAsyncThunk(
  "posts/postsingleAsync",
  async (post) => await axios.post(`http://localhost:5000/posts/`, post)
);

export const postsSlice = createSlice({
  name: "posts",
  initialState: {
    allposts: [],
    loading: "idle",
    error: "",
    selectedPost: {},
  },
  // The `reducers` field lets us define reducers and generate associated actions
  reducers: {
    selectedpost: (state, action) => {
      state.selectedPost = action.payload;
    },
    createPost: (state, action) => {
      state.allposts = [...state.allposts, action.payload];
    },
  },
  // The `extraReducers` field lets the slice handle actions defined elsewhere,
  // including actions generated by createAsyncThunk or in other slices.
  extraReducers: (builder) => {
    builder.addCase(fetchAllPostsAsync.pending, (state, action) => {
      state.allposts = [];
      state.loading = "Loading";
    });
    builder.addCase(fetchAllPostsAsync.fulfilled, (state, action) => {
      state.allposts = action.payload;
      state.loading = "loaded";
    });

    builder.addCase(fetchAllPostsAsync.rejected, (state, action) => {
      state.allposts = "data not loaded";
      state.loading = "error";
      state.error = action.error.message;
    });

    builder.addCase(postsingleAsync.fulfilled, (state, action) => {
      state.allposts.unshift(action.payload.data);
    });
  },
});

//export const { incrementByAmount } = postsSlice.actions;

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
// export const selectCount = (state) => state.posts.value;

// export const selectAllposts = createSelector(
//   (state) => ({
//     posts: state.posts,
//     loading: state.loading,
//   }),
//   (state) => state
// );

export const { selectedpost, createPost } = postsSlice.actions;
export default postsSlice.reducer;

下面是添加帖子组件

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { createPost } from "../features/posts/postsSlice";
const AddPost = () => {
  const dispatch = useDispatch();
  const [formdata, setFormData] = useState({
    _id: "",
    date: "",
    title: "",
    message: "",
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(createPost(formdata));
    setFormData({
      title: "",
      message: "",
      _id: "",
      date: "",
    });
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          placeholder="title"
          type="text"
          value={formdata.title}
          onChange={(e) => setFormData({ ...formdata, title: e.target.value })}
        />
        <input
          placeholder="message"
          type="text"
          value={formdata.message}
          onChange={(e) =>
            setFormData({ ...formdata, message: e.target.value })
          }
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default AddPost;

以下是尝试从邮递员获取时的单个帖子对象

{
    "_id": "60b9dcafbdd24791d803396b",
    "title": "ffdf",
    "message": "mybday",
    "date": "2021-06-04T07:56:31.834Z",
    "__v": 0
}

后端

下面是后端的模式模式

import mongoose from "mongoose";

const postSchemasetup = mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  message: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

const postSchema = mongoose.model("Posts", postSchemasetup);

export default postSchema;

标签: node.jsreactjsmongodbreduxecmascript-6

解决方案


推荐阅读