Ale*_*Kor 1 reactjs redux rtk-query
当我应用 createApi 自动生成的钩子时。该钩子会自动向服务器发出请求,但我只需要在特定条件下发出该请求。我尝试根据Redux文档来实现它:(https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching),但没有成功。
我的实现:(src/features/posts/PostList.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>
)
}
Run Code Online (Sandbox Code Playgroud)
根据 Redux Toolkit RTK 查询文档,我应该使用一个带有布尔跳跃属性的对象作为自动生成的钩子的参数。我做到了,但没有成功。无论如何,它一直在向服务器发出请求。那么,我到底做错了什么?
apiSlice 看起来像:(src/features/api/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
Run Code Online (Sandbox Code Playgroud)
您还可以在 GitHub 上查看此代码。GitHub链接:https://github.com/AlexKor-5/Redux_Mock_Service_Worker/tree/bd593191dce8c13982ffa2cdb946046d6eb26941
| 归档时间: |
|
| 查看次数: |
6964 次 |
| 最近记录: |