You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo Router中无合适根文件包裹QueryClientProvider,React Query配置遇阻求助

解决Expo Router集成React Query的根Provider配置问题

在Expo Router(v2及以上版本)中,app/_layout.js/tsx就是你要找的根布局文件,所有路由页面都会被这个文件的内容包裹,正好用来配置React Query的QueryClientProvider。具体步骤如下:

  • 先确保已安装React Query:

    npx expo install @tanstack/react-query
    
  • 在app目录下创建或修改_layout.tsx(或.js)文件,内容示例:

    import { Stack } from 'expo-router';
    import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
    
    // 创建全局QueryClient实例,可根据需求调整缓存策略
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 60000,
          refetchOnWindowFocus: false,
        },
      },
    });
    
    export default function RootLayout() {
      return (
        <QueryClientProvider client={queryClient}>
          <Stack>
            <Stack.Screen name="index" options={{ title: '首页' }} />
            // 可添加其他路由配置,嵌套布局场景下用<Slot />替代Stack
          </Stack>
        </QueryClientProvider>
      );
    }
    
  • 若你使用的是Expo Router v1版本,根文件为app/index.js,只需把整个路由结构包裹在QueryClientProvider内即可,但v1已不再推荐,建议升级到v2+。

  • 验证配置是否生效:在任意页面(比如app/index.tsx)用React Query的hooks测试:

    import { useQuery } from '@tanstack/react-query';
    import { Text } from 'react-native';
    
    export default function Home() {
      const { data, isLoading } = useQuery({
        queryKey: ['testData'],
        queryFn: async () => {
          const res = await fetch('https://api.example.com/data');
          return res.json();
        },
      });
    
      if (isLoading) return <Text>加载中...</Text>;
      return <Text>{JSON.stringify(data)}</Text>;
    }
    

完成以上配置后,所有页面都能直接使用React Query的hooks。

内容的提问来源于stack exchange,提问作者Karen Rayleigh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:01:03