这是我第一次使用Redux,发生的事情是我试图在材质UI选择中显示数据,当我显示用户名时,它可以完美地工作,我为合作伙伴的数据做了同样的事情,但它们未定义。
在服务器索引,我有以下代码: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);
这就是我意识到数据未定义的地方。输入图片描述
非常感谢那些能帮助我的人!
在
const { data } = useGetAllUsersQuery();
您正在正确地解构data
属性,但是问题是否在
const { data2 } = useGetPartnerQuery()
您正在解构不存在的data2
属性,其值为undefined
,相反,您应该解构data
属性并使用冒号将其重命名为data2
const { data: data2 } = useGetPartnerQuery()