我是React和web开发的新手,我知道代码风格很糟糕,但请原谅我。
我试图用openweathermap API获取天气数据,我必须为我想要的位置使用纬度和经度,当我输入我感兴趣的国家的首都和国家代码时,我应该从他们单独的地理编码API获得。
我有点不确定如何"堆叠"这些请求使得第一个坐标请求通过并将坐标提供给第二个天气请求。我的问题是,坐标(否则我将成功获得)是未定义给我的下一个请求,我不知道为什么,我已经尝试了很多。
const Content = ({result}) => {
const languages = [result['languages']]
const [weather, setWeather] = useState([])
const [coordinate, setCoordinates] = useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(() => {
axios
.get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
.then(response => {
setCoordinates(response.data)
})
.then(() =>
axios
.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
.then(response => {
setWeather(response.data)
}))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
setCoordinates
不会立即更新coordinate
,因为React批量状态更新。因此,状态是异步更新的。
如果您的第二个请求依赖于coordinate
数组的状态更改,那么您应该将其移动到自己的useEffect
钩子中:
const Content = ({result}) => {
const languages = [result['languages']]
const [weather, setWeather] = useState([])
const [coordinate, setCoordinates] = useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(() => {
axios
.get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
.then(response => {
setCoordinates(response.data)
});
}, []);
// Your second API call is dependent on state changes to `coordinate`
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
.then(response => {
setWeather(response.data)
});
}, [coordinate]);
};
const Content = ({result}) => {
const languages = [result['languages']]
const [weather, setWeather] = useState([])
const [coordinate, setCoordinates] = useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(() => {
let coordinateResult = [];
axios
.get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
.then(response => {
coordinateResult = response.data;
})
.then(() =>
axios
.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinateResult['lat']}&lon=${coordinateResult['lon']}&exclude=1&appid=${api_key}`)
.then(response => {
setCoordinates(coordinateResult);
setWeather(response.data)
}))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
注意setState
函数是异步的