mongoose 使用RTK查询时,某些数据返回未定义

3bygqnnd  于 2023-04-06  发布在  Go
关注(0)|答案(1)|浏览(125)

这是我第一次使用Redux,发生的事情是,我试图在Material UI Select中显示数据,当我显示用户名时,它工作得很好,我对合作伙伴的数据做了同样的事情,但它们到达时未定义。
在服务器索引中,我有以下代码:app.use("/client", clientRoutes);
在路线中,我有这个:

import express from "express";
import { getAllUsers, getPartner } from "../controllers/client.js";

const router = express.Router();

router.get("/users", getAllUsers);
router.get("/partners", getPartner);

export default router;

在控制器中:

import User from "../models/User.js";
import Partner from "../models/Partner.js";

export const getAllUsers = async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json(users);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
};

export const getPartner = async (req, res) => {
  try {
    const partners = await Partner.find();
    res.status(200).json(partners);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
};

在模型中:

import mongoose from "mongoose";

const PartnerSchema = new mongoose.Schema(
  {
    partner_name: {
      type: String,
      required: true,
      min: 2,
      max: 100,
    },
    partner_phone: {
      type: String,
      min: 2,
      max: 100,
    },
    partner_user: {
      type: String,
      required: true,
      min: 2,
      max: 100,
    },
    partner_password: {
      type: String,
      required: true,
      min: 2,
      max: 100,
    },
  },
  { timestamps: true }
);

const Partner = mongoose.model("Partner", PartnerSchema);
export default Partner;

在API中:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const api = createApi({
  reducerPath: "adminApi",
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_BASE_URL }),
  tagTypes: ["User", "Users", "Partners"],
  endpoints: (build) => ({
    getUser: build.query({
      query: (id) => `general/user/${id}`,
      providesTags: ["User"],
    }),
    getAllUsers: build.query({
      query: () => "client/users",
      providesTags: ["Users"],
    }),
    getPartner: build.query({
      query: () => "client/partners",
      providesTags: ["Partners"],
    }),
  }),
});

export const { useGetUserQuery, useGetAllUsersQuery, useGetPartnerQuery } = api;

在我的组件中导入以下内容:

import { useGetAllUsersQuery } from "state/api";
import { useGetPartnerQuery } from "state/api";

然后这个代码:

const { data } = useGetAllUsersQuery();
  const { data2 } = useGetPartnerQuery();
  console.log("usuarios", data);
  console.log("partners", data2);

这就是我意识到数据到达undefined的地方。enter image description here
非常感谢那些能帮助我的人!

acruukt9

acruukt91#

在…线上

const { data } = useGetAllUsersQuery();

您正确地解构了data属性,但问题是在下面的

const { data2 } = useGetPartnerQuery()

您正在解构值为undefined的不存在的data2属性,而应该解构data属性并使用冒号将其重命名为data2

const { data: data2 } = useGetPartnerQuery()

相关问题