首页 > 解决方案 > 使用 fetch 对象中的日期来创建链接以在 react 中获取另一个对象

问题描述

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

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

useEffect(() => { 
    getKey();
    getWeather();
},[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);
};

标签: javascriptreactjs

解决方案


您只需对代码进行一些细微更改即可完成这项工作。制作useEffectandasync函数,将键 from 返回getKey到变量并等待变量赋值并传递给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);
};

我返回值而不是使用 state 的原因是因为设置 state 是异步的,并且当前没有useState像 for 那样设置函数的回调函数setState


推荐阅读