reactjs 未设置QueryClient,请使用QueryClientProvider设置一个

332nm8kg  于 2022-11-04  发布在  React
关注(0)|答案(8)|浏览(547)

我第一次尝试响应查询,然后我在我的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
oxosxuxt

oxosxuxt1#

如错误所示,您需要将应用程序 Package 在QueryClientProvider中。

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

const queryClient = new QueryClient()

export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}
l2osamch

l2osamch2#

虽然这通常是由于没有将应用程序 Package 在<QueryClientProvider>中而导致的,但在我的情况下,这是因为我导入了一些共享组件,这些组件以不同的上下文结束。
这看起来像:

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:布尔值(默认为false)
将此设置为true可启用上下文共享,这将在整个窗口中共享上下文的第一个和至少一个示例,以确保如果在不同的捆绑包或微前端中使用“React查询”,则无论模块作用域如何,它们都将使用相同的上下文示例。

lc8prwob

lc8prwob3#

只要像下面这样进行更改,它就会工作正常

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')
);
2jcobegt

2jcobegt4#

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>
);

}
wn9m85ua

wn9m85ua5#

我也想解决同样的问题:
我遵循React Query docs并使用Higher Order Component的概念
看看是否有帮助:

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);
hgb9j2n6

hgb9j2n66#

单个SPA(微前端)-React查询v3.34.15

我在尝试将一个single-spa react包集成到根应用程序中时遇到此错误。
我使用craco-plugin-single-spa-application来构建CRA应用程序,以使其适应包裹。在entryconfig中,我指向了我的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文档后,我发现我唯一需要修改的是在QueryClientProvider中传递属性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查询提供程序放在了应用程序的索引中,在我的single-spa-index.cf.js中,我导入了import App from '../App',它实际上没有被提供程序 Package 。曾经,我也在应用程序索引中导入了App,它被 Package 在这里,使它在本地工作。😢😢
所以在弄明白之后,我的代码是这样的:解决方案后的代码

// 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')
)

好吧,这是很长的,但我希望它帮助的人正在经历同样的问题,因为我的。🙌🙌🙌

gk7wooem

gk7wooem7#

在我的例子中,我在一个地方从“react-query”导入,在另一个地方从“@tanstack/react-query”导入。

0wi1tuuw

0wi1tuuw8#

我在尝试添加react-querydevtools时遇到该错误。
问题是我安装它错误根据我的版本,我使用的是react-query v3.

React查询V3错误(V4正确)

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

确定用于React查询V3

import { ReactQueryDevtools } from 'react-query/devtools';

相关问题