我创建了一个所有端点的存储区,但我的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)
1条答案
按热度按时间zz2j4svz1#
这是因为您试图立即对结果进行console.log,这意味着您试图在查询仍处于加载阶段时输出getById。
您的输出将类似于: