react-query: 网络请求库
一个好用的 react-query 库
关键词
nx.$mutation/nx.$query/nx.$client
services
queries
使用
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react'
import ReactDOM from 'react-dom/client'
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import axios from 'axios'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
)
}
function Example() {
const { isPending, error, data, isFetching } = useQuery({
queryKey: ['repoData'],
queryFn: () =>
axios
.get('https://api.github.com/repos/tannerlinsley/react-query')
.then((res) => res.data),
})
if (isPending) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{' '}
<strong>✨ {data.stargazers_count}</strong>{' '}
<strong>🍴 {data.forks_count}</strong>
<div>{isFetching ? 'Updating...' : ''}</div>
<ReactQueryDevtools initialIsOpen />
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.createRoot(rootElement).render(<App />)
我的API
项目中使用
nx.$api
来调用,项目中的nx.$client
是 queryClient 实例。
export default {
request: ['/admin', 'json'],
items: [
{
items: {
posts_index: ['get', '/posts'],
posts_create: ['post', '/posts'],
posts_show: ['get', '/posts/{id}'],
posts_update: ['put', '/posts/{id}'],
posts_destroy: ['delete', '/posts/{id}'],
},
},
],
};
cheatsheet
功能 | 代码 |
---|---|
posts 列表 |
|
posts 详情 |
|
posts 更新 |
|
posts 创建 |
|
创建有返回(entity) |
|
多个 mutate 操作 |
|
参考
- https://tanstack.com/query/v5/docs/react/quick-start
- https://tanstack.com/
- https://codesandbox.io/p/devbox/tanstack-query-example-react-simple-lskn7u
- https://github.com/tannerlinsley/react-query-blog-demo
- https://stackoverflow.com/questions/70771324/how-to-handle-multiple-mutations-in-parallel-with-react-query
- https://blog.logrocket.com/deep-dive-mutations-tanstack-query/
- https://tkdodo.eu/blog/effective-react-query-keys