我的 react-query 包中的 useQuery
钩子有问题。在这里,我使用 axios 调用 API 并成功获取数据(我调试了我的应用程序)。问题是当我返回结果时,它没有保存在 useQuery 挂钩的数据变量中。这是我的代码:
import React, { useState, useEffect } from 'react';
import './Weather.css';
import axios from "axios";
import { Link } from 'react-router-dom';
import ReactLoading from 'react-loading';
import { useQuery } from 'react-query';
const Weather = () => {
const { data, isLoading, error } = useQuery(
'weather',
() =>
{
const options = {
method: 'GET',
url: process.env.REACT_APP_WEATHER_API_URL,
params: {q: 'beirut', days: '3'},
headers: {
'x-rapidapi-key': process.env.REACT_APP_WEATHER_RAPID_API_KEY,
'x-rapidapi-host': process.env.REACT_APP_WEATHER_RAPID_API_HOST
}
};
axios.request(options).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
console.error(error);
return error;
});
}
);
if(isLoading) return <ReactLoading className='loader' type='balls' color='white' height={'20%'} width={'20%'} />
if(error) return <div>Error occured</div>
return (
<div className="Weather">
{data ?
<Link to='/weather' style={{ textDecoration: 'none', color: 'white', margin: '50px' }}>
<div className="WeatherData">
<h1>{data.location.name}, {data.location.country}</h1>
<div className="CurrentTemp">
<img src={data.current.condition.icon} alt={data.current.condition.text} />
<p>{data.current.condition.text}</p>
<p>{data.current.temp_c} °C</p>
</div>
<p>Updated on: {data.current.last_updated}</p>
</div>
</Link>
: null
}
</div>
)
}
export default Weather;
答案 0 :(得分:2)
因为这个函数没有返回任何东西
() =>
{
const options = {
method: 'GET',
url: process.env.REACT_APP_WEATHER_API_URL,
params: {q: 'beirut', days: '3'},
headers: {
'x-rapidapi-key': process.env.REACT_APP_WEATHER_RAPID_API_KEY,
'x-rapidapi-host': process.env.REACT_APP_WEATHER_RAPID_API_HOST
}
};
axios.request(options).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
console.error(error);
return error;
});
}
useQuery 需要一个异步函数或一个返回 Promise 的函数<>
async () =>
{
const options = {
method: 'GET',
url: process.env.REACT_APP_WEATHER_API_URL,
params: {q: 'beirut', days: '3'},
headers: {
'x-rapidapi-key': process.env.REACT_APP_WEATHER_RAPID_API_KEY,
'x-rapidapi-host': process.env.REACT_APP_WEATHER_RAPID_API_HOST
}
};
const data = await axios.request(options).then((response) => {
console.log(response.data);
return response.data;
}).catch((error) => {
console.error(error);
return error;
});
return data; // we return some data.
}