19

我第一次尝试对查询做出反应,然后在我的 React 应用程序开始时得到了这个。 在此处输入图像描述

import React from 'react'
import { useQuery } from "react-query";

const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    )
}

export default Planets
4

6 回答 6

32

正如错误所暗示的,您需要将应用程序包装在QueryClientProvider. 这是在文档的第一页:

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

const queryClient = new QueryClient()

export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}
于 2021-01-06T06:20:36.573 回答
14

虽然这最常见的原因是没有将您的应用程序包装在<QueryClientProvider>. 您可以通过将contextSharing选项设置为来解决此问题true

那看起来像:

 import { QueryClient, QueryClientProvider } from 'react-query'
 
 const queryClient = new QueryClient()
 
 function App() {
   return <QueryClientProvider client={queryClient} contextSharing={true}>...</QueryClientProvider>
 }

来自文档:(https://react-query.tanstack.com/reference/QueryClientProvider

contextSharing:布尔值(默认为假)

将此设置为 true 以启用上下文共享,这将在窗口中共享上下文的第一个和至少一个实例,以确保如果 React Query 用于不同的包或微前端,它们都将使用相同的上下文实例,而不管模块范围。

于 2021-03-30T16:31:24.740 回答
5
import {  QueryClient, QueryClientProvider, useQuery } from 'react-query';
const queryClient = new QueryClient();
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    );
}


export default function Wraped(){
return(<QueryClientProvider client={queryClient}>
        <Planets/>
    </QueryClientProvider>
);
    
}
于 2021-02-03T03:35:38.977 回答
1

我试图解决同样的问题:

我遵循了React Query 文档 并使用了高阶组件的概念

看看是否有帮助:
import React from 'react';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';

import Planet from './Planet';

const queryClient = new QueryClient();

const fetchPlanets = async () => {
    const res = await fetch('http://swapi.dev/api/planets/');
    return res.json();
}

const Planets = () => {

    const { data, status } = useQuery('planets', fetchPlanets);

    return (
        <div>
            <h2>Planets</h2>
            { status === 'loading' && (<div>Loading data...</div>)}
            { status === 'error' && (<div>Error fetching data</div>)}
            {
                status === 'success' && (
                    data.results.map(planet =>
                        <Planet
                            key={planet.name}
                            planet={planet}
                        />
                    )
                )
            }
        </div>
    )
}

// Higher order function
const hof = (WrappedComponent) => {
    // Its job is to return a react component warpping the baby component
    return (props) => (
        <QueryClientProvider client={queryClient}>
            <WrappedComponent {...props} />
        </QueryClientProvider>
    );
};

export default hof(Planets);
于 2021-02-25T13:06:17.483 回答
1

只需进行如下更改即可正常工作

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);
于 2021-09-29T13:03:14.420 回答
0

单 SPA(微前端)- React Query v3.34.15

我在尝试将 sigle-spa react 包裹集成到根应用程序时遇到此错误。

我用于craco-plugin-single-spa-application构建 CRA 应用程序以使其适应包裹。在条目配置中,我指向我的single-spa-react配置。

// craco.config.js

const singleSpaApplicationPlugin = require('craco-plugin-single-spa-application')

module.exports = {
  plugins: [
    {
      plugin: singleSpaApplicationPlugin,
      options: {
        orgName: 'uh-platform',
        projectName: 'hosting',
        entry: 'src/config/single-spa-index.cf.js',
        orgPackagesAsExternal: false,
        reactPackagesAsExternal: true,
        externals: [],
        minimize: false 
      }
    }
  ]
}

single-spa-index.cf.js文件中,我有以下配置。

import React from 'react'
import ReactDOM from 'react-dom'

import singleSpaReact from 'single-spa-react'

import App from '../App'

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: App,
  errorBoundary() {
    return <div>Ocorreu um erro desconhecido!</div>
  }
})

export const { bootstrap, mount, unmount } = lifecycles

在阅读了一堆论坛和 react-query 文档之后,我发现我唯一需要更改的就是将QueryClientProviderprop传递contextSharing为 true。完成此更改后,运行建筑物并访问打开我的包裹的路线。我得到了同样的错误。

import React from 'react'
import ReactDOM from 'react-dom'
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import App from './App'

const queryClient = new QueryClient()

const isDevelopmentEnv = process.env.NODE_ENV === 'development'

if (isDevelopmentEnv) {
  import('./config/msw/worker').then(({ worker }) => worker.start())
}

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider contextSharing={true} client={queryClient}>
      <App />
      {isDevelopmentEnv && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

但是,我该如何解决。嗯,这很简单。我什至无法想象它为什么在本地工作。但不是在构建和集成之后。

问题是因为我将 React Query Provider 放在了应用程序的索引中,而single-spa-index.cf.js我正在导入import App from '../App'它实际上并没有被提供程序包装。有一次我还在应用程序索引中导入App,它被包装在其中,使其在本地工作。

所以在弄清楚之后,我的代码是这样的: CODE AFTER SOLUTION

// craco.config.js
const singleSpaApplicationPlugin = require('craco-plugin-single-spa-application')

module.exports = {
  plugins: [
    {
      plugin: singleSpaApplicationPlugin,
      options: {
        orgName: 'uh-platform',
        projectName: 'hosting',
        entry: 'src/config/single-spa-index.cf.js', 
        orgPackagesAsExternal: false,
        reactPackagesAsExternal: true,
        externals: [], 
        minimize: false 
      }
    }
  ]
}

// src/config/single-spa-index.cf.js 
import React from 'react'
import ReactDOM from 'react-dom'

import singleSpaReact from 'single-spa-react'

import App from '../App'

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: App,
  errorBoundary() {
    return <div>Ocorreu um erro desconhecido!</div>
  }
})

export const { bootstrap, mount, unmount } = lifecycles


// App.tsx
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import { config } from 'config/react-query'
import Routes from 'routes'
import GlobalStyles from 'styles/global'

import * as S from './styles/shared'

const queryClient = new QueryClient(config)

const isDevelopmentEnv = process.env.NODE_ENV === 'development'

if (isDevelopmentEnv) {
  import('./config/msw/worker').then(({ worker }) => worker.start())
}

function App() {
  return (
    <QueryClientProvider contextSharing={true} client={queryClient}>
      <S.PanelWrapper>
        <Routes />
        <GlobalStyles />
      </S.PanelWrapper>

      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

export default App

// index.tsx
import { StrictMode } from 'react'
import ReactDOM from 'react-dom'

import App from './App'

ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  document.getElementById('root')
)

好吧,它很长,但我希望它可以帮助那些正在经历与我相同问题的人。

于 2022-02-16T13:31:30.407 回答