我创建了一个存储,其中是一个所有端点,并且我的getById端点有问题。
Store.tsx
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { Character } from "../interface/types";
export const characterAPI = createApi({
reducerPath: "characterAPI",
baseQuery: fetchBaseQuery({ baseUrl: "https://www.breakingbadapi.com/api/" }),
tagTypes: ["Characters"],
endpoints: (builder) => ({
getAll: builder.query<Character[], void>({
query: () => `characters`,
providesTags: [{ type: "Characters", id: "LIST" }],
}),
getById: builder.query<Character, string>({
query: (char_id) => `characters/${char_id}`,
providesTags: [{ type: "Characters", id: "LIST" }],
}),
}),
});
CharacterContainer.tsx
但加载后我可以看到整个数据,但当我想要console.log(getById(时,它会显示未定义的
import React from "react";
import { useParams } from "react-router-dom";
import { characterAPI } from "../store/store";
const CharacterContainer = () => {
const { char_id } = useParams();
const { data: getById, isLoading } = characterAPI.useGetByIdQuery(
char_id as string
);
console.log(getById);
const { name, birthday } = getById || {};
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
<p>{name}</p>
<p>{birthday}</p>
</div>
);
};
我在工具中看到的:
CharacterContainer.tsx:22 undefined
CharacterContainer.tsx:22 undefined
CharacterContainer.tsx:22
[{…}]0: appearance: (5) [1, 2, 3, 4, 5]
better_call_saul_appearance: []
birthday: "09-07-1958"
category: "Breaking Bad"
char_id: 1
img: "https://images.amcnetworks.com/amc.com/wpcontent/uploads/2015/04/cast_bb_700x1000_walter-white-lg.jpg"
name: "Walter White"
nickname: "Heisenberg"
occupation: (2)
['High School Chemistry Teacher', 'Meth King Pin']
portrayed: "Bryan Cranston"status:
"Presumed dead"[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)
这是因为您试图立即对结果进行console.log,这意味着您试图在查询仍处于加载阶段时输出getById。你可以做一些类似的事情:
console.log(isLoading ? "Loading result" : getById)
你的输出会是这样的:
CharacterContainer.tsx:22 undefined
CharacterContainer.tsx:22 undefined
CharacterContainer.tsx:22
[{…}]0: appearance: (5) [1, 2, 3, 4, 5]
better_call_saul_appearance: []
birthday: "09-07-1958"
category: "Breaking Bad"
char_id: 1
img: "https://images.amcnetworks.com/amc.com/wpcontent/uploads/2015/04/cast_bb_700x1000_walter-white-lg.jpg"
name: "Walter White"
nickname: "Heisenberg"
occupation: (2)
['High School Chemistry Teacher', 'Meth King Pin']
portrayed: "Bryan Cranston"status:
"Presumed dead"[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)