7

如何使用 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/>。它正在使用useState钩子。值正确更新并被useGetPostsByYearQuery调用,但end参数始终未定义。所以,看来我没有正确定义 api 端点。有什么建议吗?我想要它做的就是在表单中发送一个请求http://xxx/posts?start=start&end=end

我什至尝试硬编码end参数的字符串值,例如useGetPostsByYearQuery(year, '2019'),但它仍然显示为undefined带有 api 回调,所以我错过了一些更基本的东西。

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;
4

1 回答 1

15

QueryArg泛型类型。

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

源代码

从文档定义查询端点

如果query回调需要其他数据来生成 URL,则应将其编写为采用单个参数。如果您需要传入多个参数,请将它们格式化为单个“选项对象”。

因此,您可以像这样声明方法的泛型参数QueryArg类型builder.query

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"

于 2021-06-28T08:01:49.423 回答