0

我正在使用 React Query 并尝试从 JSON 文件内联获取数据(用户)。

我已经用npm React-query& React-query-devtools 安装了它,并且只有 2 个文件。

App.js

import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query-devtools';
import Users from './Users';

function App() {
  return (
    <div className="App">
      <QueryClientProvider client={QueryClient}>
        <Users />
        <ReactQueryDevtools initialIsOpen />
      </QueryClientProvider>
    </div>
  );
}

export default App;

Users.js

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

const Users = () => {
    const { isLoading, isError, data, error } = useQuery('test', () => (
        fetch('https://jsonplaceholder.typicode.com/users').then((res) => res.json())
    ));
    return (
        <div>
            {isLoading ? <h2>Chargement...</h2> : null}
            {isError ? <h2>Une erreur est survenue : {error.message}</h2> : null}

            <ul>
                {data.map((user) => (
                    <li key={user.id}>{user.name}</li>
                ))}
            </ul>
        </div>
    )
}

export default Users

我无法解决此错误:

TypeError: queryClient.defaultQueryObserverOptions is not a function
4

1 回答 1

3

您应该不直接使用QueryClientfor的实例。cleintQueryClient

根据文档

import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query-devtools';
import Users from './Users';

// Create a client
const queryClient = new QueryClient() // Instance of QueryClient

function App() {
  return (
    <div className="App">
      <QueryClientProvider client={queryClient}> // <-- here
        <Users />
        <ReactQueryDevtools initialIsOpen />
      </QueryClientProvider>
    </div>
  );
}

export default App;
于 2021-01-08T09:24:07.380 回答