首页 > 解决方案 > 将值传递给反应中 useEffect 中的 fetch 调用

问题描述

我从运行良好的用户浏览器获取地理定位,我可以在屏幕上显示 lon 和 lat,但是一旦我尝试将我的数据位置推送到我的 useEffect 中的 fetch 调用,我并没有真正做错了什么。 .我收到错误 TypeError: Cannot read property 'photo' of undefined 似乎数据没有被推送到 fetch 或者在这种情况下 lon 和 lat 可能为空

import React, { useEffect, useState } from 'react';
import './App.css';
import Map from './Componets/Map/Map';
import Location from './Componets/Api/Location';
import List from './Componets/List/List';
import Test from './Componets/test/Test';

require('dotenv').config();

const App = () => {
    const [
        Locations,
        setLocations
    ] = useState([]);

    const [
        GoeLocationlng,
        setGoeLocationlng
    ] = useState('');
    const [
        GoeLocationlat,
        setGoeLocationlat
    ] = useState('');

    const [
        Imgdata,
        setImgdata
    ] = useState([]);

    const [
        search,
        setSearch
    ] = useState('');

    const [
        query,
        setQuery
    ] = useState('bar');

    useEffect(
        () => {
            async function example(lon, lat) {
                let response1 = await fetch(
                    `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=9c348b767f7a0403e907b0788188afba&text=${query}&tags=new&accuracy=+11&media=photos+&geo_context=1&per_page=20&page=1&lat=${parseFloat(
                        lat
                    )}&lon=${parseFloat(lon)}&radius=10&radius_units=km&format=json&nojsoncallback=1`
                );
                let json = await response1.json();

                const promises = json.photos.photo.map((i) =>
                    fetch(
                        `https://www.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=9c348b767f7a0403e907b0788188afba&photo_id=${i.id}&format=json&nojsoncallback=1`
                    )
                );

                const response2 = await Promise.all(promises);

                const json2 = await Promise.all(response2.map((res) => res.json()));

                return {
                    dataset1: json,
                    dataset2: json2
                };
            }
            example(GoeLocationlng, GoeLocationlat)
                .then((i) => {
                    setLocations(i.dataset1.photos.photo);
                    // console.log(i.dataset2.photo);
                    setImgdata(i.dataset2);
                })
                .catch((err) => {
                    console.log(err);
                });
            getLocation();
        },
        [
            query
        ]
    );

    const updateSearch = (event) => {
        setSearch(event.target.value);
    };

    const getSearch = (event) => {
        event.preventDefault();
        setQuery(search);
        // setLocations({});
        setSearch('');
    };

    const getLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(getCods);
        } else {
            alert('Geolocation is not supported by this browser.');
        }
    };

    const getCods = (postion) => {
        setGoeLocationlat(postion.coords.latitude);
        setGoeLocationlng(postion.coords.longitude);
    };
    getLocation();

    return (
        <div className="App">
            <Map
                googleMapURL={`https://maps.googleapis.com/maps/api/js?key=AIzaSyA8i9z0T-J6oIs6Rrb7FUqz0rM1jipwrEg&v=3.exp&libraries=geometry,drawing,places`}
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `400px` }} />}
                mapElement={<div style={{ height: `100%` }} />}
                Locations={{ Imgdata }}
            />
            <form onSubmit={getSearch} className="searchForm">
                <input className="search-bar" type="text" onChange={updateSearch} />
                <button className="search-btn" type="submit" value="Search">
                    Search
                </button>
            </form>
            {/* {Locations.map((location) => <Location key={location.id} title={location.title} />)} */}

            {Locations.map((location) => (
                <List
                    key={location.id}
                    title={location.title}
                    farm={location.farm}
                    server={location.server}
                    id={location.id}
                    secret={location.secret}
                />
            ))}

            <h1>{GoeLocationlng}</h1>
        </div>
    );
};
export default App;

标签: javascriptapifetchreact-hooksuse-effect

解决方案


您应该再次检查您的 api,它无法正常工作。它会导致错误 TypeError: Cannot read property 'photo' of undefined。


推荐阅读