当我从createApi应用一个自动生成的钩子时。这个钩子向服务器发出自动请求,但我只需要在特定条件下发出请求。我尝试根据Redux文档实现它:(https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching),但没有成功。
我的实现:(来源/功能/帖子/帖子列表. js)
import React, { useState } from 'react'
import { useGetPostsQuery } from '../api/apiSlice'
const PostExcerpt = ({ post }) => {
return (
<div>
<p>{post.postText}</p>
<p>
<small>{post.author}</small>
</p>
</div>
)
}
export const PostList = () => {
const [skip, setSkip] = useState(true)
const { data: posts = [], isLoading, isSuccess, isError, error } = useGetPostsQuery({ skip })
let content
if (isLoading) {
content = <h3>Posts Loading ...</h3>
} else if (isSuccess) {
content = posts.map(post => <PostExcerpt key={post.id} post={post} />)
} else if (isError) {
content = (
<div>
<h3>Error happened</h3>
<p>
<small>{error.toString()}</small>
</p>
</div>
)
}
return (
<div style={{ border: '2px solid red' }}>
<h2>Posts:</h2>
<button onClick={() => setSkip(prev => !prev)}>Fetch it</button>
{content}
</div>
)
}
根据Redux Toolkit RTK Query文档,我应该使用一个带有boolean skip属性的对象作为自动生成的钩子的参数。我这样做了,但没有成功。它一直在向服务器发出请求。那么,我做错了什么呢?
apiSlice看起来像:(源代码/功能/应用程序/应用程序切片. js)
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
// Define our single API slice object
export const apiSlice = createApi({
// The cache reducer expects to be added at `state.api` (already default - this is optional)
reducerPath: 'api',
// All of our requests will have URLs starting with '/fakeApi'
baseQuery: fetchBaseQuery({ baseUrl: '/fakeApi' }),
// The "endpoints" represent operations and requests for this server
endpoints: builder => ({
// The `getPosts` endpoint is a "query" operation that returns data
getPosts: builder.query({
// The URL for the request is '/fakeApi/posts'
query: () => '/posts',
}),
addNewPost: builder.mutation({
query: initialPost => ({
url: '/posts',
method: 'POST',
body: initialPost,
}),
}),
}),
})
// Export the auto-generated hook for the `getPosts` query endpoint
export const { useGetPostsQuery, useAddNewPostMutation } = apiSlice
您也可以在GitHub上查看此代码。GitHub链接:https://github.com/AlexKor-5/Redux_Mock_Service_Worker/tree/bd593191dce8c13982ffa2cdb946046d6eb26941
3条答案
按热度按时间jgzswidk1#
选项始终是第二个参数-您需要
a8jjtwal2#
您将'skip'作为查询的参数传递,但它是一个选项,因此必须位于挂接的第二个参数中。如果查询没有参数,则可以传递'null'或'undefined'
x3naxklr3#
如果不需要参数,也可以使用skiptoken(而不是传递假的第一个参数)以及useLazyQuery钩子,它“类似于useQuery,但可以手动控制数据获取的时间”