如何使用 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;