简体   繁体   English

如何使用 RTK 查询从 API 获取特定数据?

[英]how to fetch specific data from API using RTK Query?

firstly I am new to RTK Query.首先,我是 RTK 查询的新手。 I am trying to fetch some specific data from API but I don't understand how to do it.我正在尝试从 API 获取一些特定数据,但我不知道该怎么做。 If anyone can help me it will be great.如果有人可以帮助我,那就太好了。

My API link: https://api.spacexdata.com/v3/launches我的 API 链接: https ://api.spacexdata.com/v3/launches

I just need some specific data like flight_number, mission_name, upcoming, launch_date_utc, rocket_name, launch_success, mission_patch_small .我只需要一些特定的数据,例如flight_number、mission_name、commoning、launch_date_utc、rocket_name、launch_success、mission_patch_small

I already fetched data but can't able to fetch particular data what I want, don't understand how to do it.我已经获取了数据,但无法获取我想要的特定数据,不知道该怎么做。

My code: App.tsx:我的代码: App.tsx:

import { useMissionsQuery, useMissionQuery } from "./services/missionsApi";
import "./App.css";

const App = () => {
  const { data, error, isLoading, isFetching, isSuccess } = useMissionsQuery();

  return (
    <div className="App">
      <h1>SpaceX Launches: Mission</h1>
      {isLoading && <h2>...Loading</h2>}
      {isFetching && <h2>...Fetching</h2>}
      {error && <h2>Something went wrong</h2>}
      {isSuccess && (
        <div>
          {data?.map((mission) => {
            return (
              <div className="data" key={mission.flight_number}>
                <span>{mission.mission_name}</span>
                <span>
                  <MissionDetail flight_number={mission.flight_number} />
                </span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export const MissionDetail = ({ flight_number }: { flight_number: string }) => {
  const { data } = useMissionQuery(flight_number);
  return <pre>{JSON.stringify(data, undefined, 2)}</pre>;
};

export default App;

services/missionsApi.tsx:服务/missionsApi.tsx:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { Mission } from "../models/mission.model";

export const missionsApi = createApi({
  reducerPath: "missionsApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://api.spacexdata.com/v3/launches",
  }),
  endpoints: (builder) => ({
    missions: builder.query<Mission[], void>({
      query: () => "/",
    }),
    mission: builder.query<Mission, string>({
      query: (flight_number) => `/${flight_number}?`,
    }),
  }),
});

export const { useMissionsQuery, useMissionQuery } = missionsApi;

model mission.model.ts:模型mission.model.ts:

export interface Mission {
  flight_number: string;
  mission_name: string;
  upcoming: string;
  launch_date_utc: string;
  rocket: string;
  rocket_name: string;
  launch_success: string;
  links: string;
  mission_patch_small: string;
}

and store.ts存储.ts

import { configureStore } from "@reduxjs/toolkit";
import { missionsApi } from "./services/missionsApi";

export const store = configureStore({
  reducer: {
    [missionsApi.reducerPath]: missionsApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(missionsApi.middleware),
});

My first thought is the same as @phry -- you are already doing this correctly , You have already fetched all of the data that you need: and you are already displaying individual properties:我的第一个想法与@phry 相同——你已经正确地做到了这一点,你已经获取了你需要的所有数据:并且你已经在显示各个属性:

<span>{mission.mission_name}</span>

Keep doing that!继续这样做!


Having looked at the API response, you don't actually need to be making any API calls in your MissionDetail component.查看 API 响应后,您实际上不需要在MissionDetail组件中进行任何 API 调用。 The list that gets returned from the useMissionsQuery in the App component is giving lots of data about each mission in the list.App组件中的useMissionsQuery返回的列表提供了有关列表中每个任务的大量数据。

You should create a render component that takes the Mission object and displays its information.您应该创建一个渲染组件,它接受Mission对象并显示其信息。

function MissionDetail({ mission }: { mission: Mission }) {
  return (
    <div className="data">
      <div>Flight Number: {mission.flight_number}</div>
      <div>Name: {mission.mission_name}</div>
      <div>Launch Date: {mission.launch_date_utc}</div>
    </div>
  );
}

Then your home page can pass each item in the array off to the MissionDetail component to render it.然后您的主页可以将数组中的每个项目传递给MissionDetail组件以呈现它。 You can simplify your loop to this:您可以将循环简化为:

{data?.map((mission) => (
  <MissionDetail key={mission.flight_number} mission={mission} />
))}

(though it seems like flight_number is not a unique key) (虽然看起来flight_number不是唯一键)

You might have other places in your app where you want to render a specific mission by its flight_number , like on a detail page for a mission.您可能在应用程序的其他位置希望通过其flight_number呈现特定任务,例如在任务的详细信息页面上。 That would be where you'd want to call useMissionQuery(flight_number) .那就是您要调用useMissionQuery(flight_number)的地方。

function MissionByFlightNumber({ flight_number }: { flight_number: string }) {
  const { data, isError, isLoading, isSuccess } = useMissionQuery(flight_number);
  return (
    <div>
      {isLoading && <h2>...Loading</h2>}
      {isError && <h2>Something went wrong</h2>}
      {isSuccess && data && <MissionDetail mission={data} />}
    </div>
  );
}

Code Sandbox 代码沙箱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM