使用 React Query 手动获取时显示 "No results" 消息

Displaying "No results" message when manually fetching with React Query

所以这是我第一次尝试使用 React Query 手动获取数据,我正在构建一个简单的天气预报应用程序,但我确实遇到了一个小“问题”:

我想要的是当由于某种原因(例如,用户输入疯狂的东西)数据不可用时,显示“未找到结果”消息。

问题是第一次安装组件时,React Query 的数据状态将是未定义的,所以我不能依赖它来显示无结果消息,因为即使有人第一次访问它也会显示该应用程序的时间...任何想法如何仅在数据不可用时显示该消息?

这是我的代码:

import './App.css';
import Form from "./components/Form.jsx";
import { useQuery } from 'react-query';
import { useState } from 'react';
import { fetchData } from './api/httpRequest';
import Card from "./components/Card";


function App() {
  const [search, setSearch] = useState("");

  const { data: info, isFetching, isError, refetch } = useQuery("info",
    () => fetchData(search), {
    enabled: false,
    refetchOnWindowFocus: false,
  });


  console.log(info);

  return (

    <main className="App">
      <h1 className="app-title">Weather Forecast App</h1>
      <Form search={search} setSearch={setSearch} fetch={refetch} />
      {isFetching ? "Loading..." : isError ? "Error!" : !info ? "No results" : <Card forecast={info} />}
    </main>

  );
}

export default App;

这些是抓取函数:

import axios from "axios";

const API_WEATHER = "https://api.openweathermap.org/data/2.5/onecall?";
const API_WEATHER_EXCLUDE = "&exclude=minutely,hourly,alerts";
const API_COORDINATES = "http://api.positionstack.com/v1/forward?";

const getCoordinates = async (query) => {
    try {
        const response = await axios.get(API_COORDINATES + "access_key=" + process.env.REACT_APP_API_COORDS_KEY + "&query=" + query + "&limit=1");
        return response.data.data[0];
    }
    catch (error) {
        console.log(error);
    }
}

export const fetchData = async (query) => {
    try {
        const coords = await getCoordinates(query);
        const response = await axios.get(API_WEATHER + "lat=" + coords.latitude + "&lon=" + coords.longitude + API_WEATHER_EXCLUDE + "&appid=" + process.env.REACT_APP_API_WEATHER_KEY);
        return response.data;

    }
    catch (error) {
        console.log(error);
    }
}

您始终可以使用状态状态 (status === 'success') 而不是 isFetching,如 documentations 中所述:

function Todos() {
   const { status, data, error } = useQuery('todos', fetchTodoList)
 
   if (status === 'loading') {
     return <span>Loading...</span>
   }
 
   if (status === 'error') {
     return <span>Error: {error.message}</span>
   }
 
   // also status === 'success', but "else" logic works, too
   return (
     <ul>
       {data.map(todo => (
         <li key={todo.id}>{todo.title}</li>
       ))}
     </ul>
   )
 }

我不确定您总体上处理 returned 数据的方式。我认为最好不要使用 !info 检查 returned 结果,因为它可以 return 一个 JSON 数据与其他杂项数据以及空数据。