reactjs Redux Toolkit RTK查询发送查询参数

pkln4tw6  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(256)

如何使用Redux Toolkit RTK Query将查询参数传递给API?

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

const baseUrl = 'xxxxxxx';

export const postsApi = createApi({
  reducerPath: 'posts',
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getPostsByYear: builder.query({
      query: (start, end) => { // Why is 'end' always undefined???
        return {
          url: 'posts/',
          params: { start, end },
        };
      },
    }),
    getPosts: builder.query({
      query: () => 'posts/',
    }),

    getPostByID: builder.query({
      query: (name) => `posts/${name}`,
    }),
  }),
});

export const { useGetPostsQuery, useGetPostsByYearQuery, useGetPostByIDQuery } = postsApi;

当尝试从组件传递参数时,似乎只能识别start值。year<PostOptions/>组件中的select元素更新。它使用useState钩子。值正确更新,并调用useGetPostsByYearQuery,但end参数始终未定义。因此,看起来我没有正确定义API端点。有什么建议吗?我想要它做的就是发送一个http://xxx/posts?start=start&end=end的请求。
我甚至尝试过为end参数硬编码一个字符串值,例如useGetPostsByYearQuery(year, '2019'),但是在API回调中它仍然显示为undefined,所以我遗漏了一些更基本的东西。

const Post = () => {
 
  const year = useSelector((state) => state.postOptions.year);
  const yearPlusOne = parseInt(year, 10) + 1;
  const { data, error, isLoading } = useGetPostsByYearQuery(year, yearPlusOne);

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <PostHeading />
        <PostOptions></PostOptions>
      </View>
    </SafeAreaView>
  );
};

export default Post;
jgzswidk

jgzswidk1#

QueryArg是泛型类型。

interface EndpointDefinitionWithQuery<
  QueryArg,
  BaseQuery extends BaseQueryFn,
  ResultType
> {
  query(arg: QueryArg): BaseQueryArg<BaseQuery>
}

参见源代码。
从定义查询端点的文档:
如果query回调函数需要额外的数据来生成URL,那么它应该被写成只带一个参数。如果你需要传入多个参数,那么就把它们格式化为一个"选项对象"。
因此,您可以像这样为builder.query方法声明泛型参数QueryArg类型:

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

const baseUrl = 'xxxxxxx';

export const postsApi = createApi({
  reducerPath: 'posts',
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getPostsByYear: builder.query<any, { start: string; end: string }>({
      query: (arg) => {
        const { start, end } = arg;
        console.log('arg: ', arg);
        return {
          url: 'posts/',
          params: { start, end },
        };
      },
    }),
  }),
});

export const { useGetPostsByYearQuery } = postsApi;

并像这样传递查询参数:

import React from 'react';
import { useGetPostsByYearQuery } from './hooks';

export default function App() {
  const { data, error, isLoading } = useGetPostsByYearQuery({ start: '2019', end: '2021' });
  return <div>app</div>;
}

日志:

arg:  { start: '2019', end: '2021' }

版本:"@reduxjs/toolkit": "^1.6.0"

相关问题