gpt4 book ai didi

javascript - 使用来自获取对象的日期创建链接以获取 react 中的另一个对象

转载 作者:行者123 更新时间:2023-11-30 13:54:55 26 4
gpt4 key购买 nike

我写了一些代码并工作了,但我认为也许可以用更好的方法来完成。我想从代码中得到什么?我创建链接并从该对象获取对象我想使用一些值并在获取新对象之后在另一个链接中传递该值。我的代码有效,但我想看看是否有可能的新解决方案。

const [key, setKey] = useState("");
const [data, setData] = useState([]);

useEffect(() => {
getKey();
getWeather();
},[key]);

//此函数从对象获取 key ,我将在另一个链接中使用该 key

const getKey = () => {
navigator.geolocation.getCurrentPosition(

(position) => {
const long = JSON.stringify(position.coords.longitude);
const lat = JSON.stringify(position.coords.latitude);

const proxy = `https://cors-anywhere.herokuapp.com/`;
const link = `${proxy}http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=rhlYEhvAu0nhFNMFybOIhffbmjFX0AZN&q=${lat}%2C${long}&details=true`;

(async function fetchData(){
const getValue = await fetch (link);
const key = await getValue.json();
setKey(key.Key);
})();
}
);
};

const getWeather = async () => {
const proxy = `https://cors-anywhere.herokuapp.com/`;
const link = `${proxy}http://dataservice.accuweather.com/forecasts/v1/daily/5day/${key}?apikey=rhlYEhvAu0nhFNMFybOIhffbmjFX0AZN&details=true&metric=true`;
const data = await fetch (link);
const getData = await data.json();
setData(getData);
};

最佳答案

您只需对代码稍作改动即可完成这项工作。创建 useEffectasync 函数,将 getKey 中的 key 返回给变量并等待变量分配并传递给 getWeather。像这样:

const [key, setKey] = useState("");
const [data, setData] = useState([]);

useEffect(async() => { // <---- Converted to async
const apiKey = getKey(); // <---- Assigned to variable
getWeather(await apiKey); // <--- Using apiKey in function rather than just state
},[key]);

const getKey = () => {
navigator.geolocation.getCurrentPosition(

(position) => {
const long = JSON.stringify(position.coords.longitude);
const lat = JSON.stringify(position.coords.latitude);

const proxy = `https://cors-anywhere.herokuapp.com/`;
const link = `${proxy}http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=rhlYEhvAu0nhFNMFybOIhffbmjFX0AZN&q=${lat}%2C${long}&details=true`;

(async function fetchData(){
const getValue = await fetch (link);
const key = await getValue.json();
setKey(key.Key);
return key.Key //<------ returned key for useEffect
})();
}
);
};

const getWeather = async (apiKey = key) => { // <----If no value passed to function, will use state value
const proxy = `https://cors-anywhere.herokuapp.com/`;
const link = `${proxy}http://dataservice.accuweather.com/forecasts/v1/daily/5day/${apiKey}?apikey=rhlYEhvAu0nhFNMFybOIhffbmjFX0AZN&details=true&metric=true`;
const data = await fetch (link);
const getData = await data.json();
setData(getData);
};

我返回值而不是使用状态的原因是因为设置状态是异步的,目前没有像 setState 那样的 useState 设置函数的回调函数.

关于javascript - 使用来自获取对象的日期创建链接以获取 react 中的另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com