React-query 系列第 1 部分:基本 react-query 设置
嘿大家!
所以,在做了几年前端开发者之后,我决定
写我的第一篇文章。你不知道我克服了多少恐惧
(或许你知道),😟 但躲在壳里也没意义,对吧?
章节
简介
React-query是一个用于获取、更新和同步服务器状态的超轻量级库。使用 React-query,你无需编写
数据获取逻辑(谁会喜欢那些加载、错误和数据状态的设置呢?🤷♀️),
也无需像 redux 或
zustand 这样的全局存储库来将服务器状态设置为全局或持久化。即使
你的应用程序中使用了全局存储库,它也仅限于
客户端状态,例如用户设置等,从而
大大减少了代码量。
虽然这个库的文档很精彩,但我发现它对初学者来说可能令人望而生畏,因此需要一个简洁易懂的系列教程来帮助初学者快速上手使用 React-query。
你也可以直接跳到本系列的第二部分:QueryClient 配置。
先决条件
- React 基础知识以及 React 中的 hooks
引导我们的项目
我们通过运行npx create-react-app project-name
npx create-react-app react-query-setup
我们还通过运行以下命令将 react-query 库安装到我们的 React 应用程序中
npm i react-query
撰写本文时,react-query版本为 3.19.6
npm i react-query
设置 react-query
要设置 React-Query,我们需要QueryClientProvider
。该QueryClientProvider
组件用于连接QueryClient
您的应用程序并提供 ;或多或少,将我们的
应用程序连接到 React-Query 提供的功能。
该QueryClientProvider
组件接收一个client
prop。该
prop 反过来又提供给实例。如果您想设置自己的默认值,queryClient
可以向实例提供
一个queryClient
自定义配置对象作为 。您可以在此处阅读 React-Query 附带的一些重要默认值。param
import { QueryClient, QueryClientProvider } from 'react-query';
/*create and use a custom config object.Normally, I'd put this in another file and export
*/
const queryClientConfig = {
defaultOptions: {
queries: {
retry: 2,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
cacheTime: 1000*30, //30 seconds
refetchInterval: 1000*30, //30 seconds
refetchIntervalInBackground: false,
suspense: false,
staleTime: 1000 * 30,
},
mutations: {
retry: 2,
},
},
const queryClient = new QueryClient(queryClientConfig)
function App() {
return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
}
此外,您还可以添加ReactQueryDevTools
组件来在开发环境中调试和可视化您的查询。
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
/*create and use a custom config object.Normally, I'd put this in another file and export
*/
const queryClientConfig = {
defaultOptions: {
queries: {
retry: 2,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
cacheTime: 1000*30, //30 seconds
refetchInterval: 1000*30, //30 seconds
refetchIntervalInBackground: false,
suspense: false,
staleTime: 1000 * 30,
},
mutations: {
retry: 2,
},
},
const queryClient = new QueryClient(queryClientConfig)
function App() {
return <QueryClientProvider client={queryClient}>
{/* The rest of your application */}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
}
在本系列的下一部分中,我们将进一步讨论对象中每个键值queryClientConfig
对查询和变异的作用。
如果这篇文章对你有帮助,请给我一个💖,
非常感谢!
在推特上关注我@NnajioforEmma10
致谢
图片:Logrocket:Lawrence Eagles 撰写的 react-query 3 中有哪些新功能。