错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数,但得到:未定义。检查`Map`的渲染方法

问题描述 投票:0回答:2

我是 React 新手,我收到以下错误:

错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入。

检查`Map`的渲染方法。

  24 |        getPlacesData(bounds.sw, bounds.ne)
  25 |        .then((data) => {
  26 |            //console.log(data);
> 27 |            setPlaces(data);
  28 |        })
  29 |    }, [coordinates, bounds]);
  30 | 

我正在关注 YouTube 视频:https://www.youtube.com/watch?v=GDa8kZLNhJ4&list=PL6QREj8te1P6wX9m5KnicnDVEucbOPsqR&index=10 特别是时间戳 1:23:00

我有三个文件,App.js、Map.js、index.js(用于 API 调用)。我正在尝试将我的坐标本地的餐厅(显示在地图容器右侧的列表中)作为图标呈现在地图上。

这是 App.js 的代码:

const App = () => {

    const [places, setPlaces] = useState([]);

    const [coordinates, setCoordinates] = useState({});
    const [bounds, setBounds] = useState({});

    useEffect(() => {
        navigator.geolocation.getCurrentPosition(({coords: {latitude, longitude}})=> {
            setCoordinates({lat: latitude, lng: longitude});
        })
    }, []);

    useEffect(() => {
        getPlacesData(bounds.sw, bounds.ne)
        .then((data) => {
            //console.log(data);
            setPlaces(data);
        })
    }, [coordinates, bounds]);

    return (
        <React.Fragment>
            <CssBaseline />
            <Header />
            <Grid container spacing={3} style={{width: '100%'}}>
                <Grid item xs={12} md={4}>
                    <List 
                        places={places}
                    />
                </Grid>
                <Grid item xs={12} md={8}>
                    <Map 
                        setCoordinates={setCoordinates}
                        setBounds = {setBounds}
                        coordinates={coordinates}
                        places={places}
                    />
                </Grid>

            </Grid>
        </React.Fragment>
        
    );
}

这是 Map.js 的代码,特别是 组件:

const Map = ({setCoordinates, setBounds, coordinates, places}) => {
    const classes = useStyles();
    const isDesktop = useMediaQuery('(min-width:600px)');

    //const coordinates = {lat: 0, lng: 0};

    return(
        <div className={classes.mapContainer}>
            <GoogleMapReact
                bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAPS_API_KEY }}
                defaultCenter={coordinates}
                center={coordinates}
                defaultZoom={14}
                margin={[50, 50, 50, 50]}
                options={{}}
                onChange={(e) => {
                setCoordinates({ lat: e.center.lat, lng: e.center.lng});
                setBounds({ne: e.marginBounds.ne, sw: e.marginBounds.sw});
                }}
                onChildClick={''}
            >
                {places && places.map((place, i) => (
                    <div
                        className={classes.markerContainer}
                        lat={Number(place.latitude)}
                        lng={Number(place.longitude)}
                        key={i}
                    >
                        {
                            isDesktop ? (
                                <LocationOnOutlinedIcon 
                                    color="primary" fontSize="large"
                                />
                            ) : (
                                <Paper elevation={3} className={classes.paper}>
                                    <Typography className={classes.typography} variant="subtitle2" gutterBottom>
                                        {place.name}
                                    </Typography>
                                    <img 
                                        className={classes.pointer}
                                        src = {place.photo ? place.photo.images.large.url : 'https://www.foodserviceandhospitality.com/wp-content/uploads/2016/09/Restaurant-Placeholder-001.jpg'}
                                        alt={place.name}

                                    />
                                </Paper>
                            )
                        }

                    </div>
                ))}
            </GoogleMapReact>

        </div>
    );
}

我检查了控制台,收到以下错误:

TypeError: Cannot read properties of undefined (reading 'lat')     at Object._callee$ (index.js:10:1)     at tryCatch (runtime.js:62:1)     at Generator.invoke [as _invoke] (runtime.js:296:1)     at prototype.<computed> [as next] (runtime.js:114:1)     at step (App.js:56:1)     at App.js:56:1     at new Promise (<anonymous>)     at App.js:56:1     at getPlacesData (index.js:6:1)     at App.js:24:1     at invokePassiveEffectCreate (react-dom.development.js:23487:1)     at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)     at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)     at invokeGuardedCallback (react-dom.development.js:4056:1)     at flushPassiveEffectsImpl (react-dom.development.js:23574:1)     at unstable_runWithPriority (scheduler.development.js:468:1)     at runWithPriority$1 (react-dom.development.js:11276:1)     at flushPassiveEffects (react-dom.development.js:23447:1)     at performSyncWorkOnRoot (react-dom.development.js:22269:1)     at react-dom.development.js:11327:1     at unstable_runWithPriority (scheduler.development.js:468:1)     at runWithPriority$1 (react-dom.development.js:11276:1)     at flushSyncCallbackQueueImpl (react-dom.development.js:11322:1)     at flushSyncCallbackQueue (react-dom.development.js:11309:1)     at unbatchedUpdates (react-dom.development.js:22438:1)     at legacyRenderSubtreeIntoContainer (react-dom.development.js:26020:1)     at Object.render (react-dom.development.js:26103:1)     at ./src/index.js (index.js:5:1)     at __webpack_require__ (bootstrap d5fbf406eb4fa0b6ffa5:678:1)     at fn (bootstrap d5fbf406eb4fa0b6ffa5:88:1)     at 0 (index.js:5:1)     at __webpack_require__ (bootstrap d5fbf406eb4fa0b6ffa5:678:1)     at bootstrap d5fbf406eb4fa0b6ffa5:724:1     at bootstrap d5fbf406eb4fa0b6ffa5:724:1

这是index.js代码:

import axios from 'axios';

const URL = 'https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary';

  
export const getPlacesData = async(sw, ne) => {
    try {
        const {data:{data}} = await axios.get(URL, {
            params: {
              bl_latitude: sw.lat,
              tr_latitude: ne.lat,
              bl_longitude: sw.lng,
              tr_longitude: ne.lng,
            },
            headers: {
              'X-RapidAPI-Key': 'API Key',
              'X-RapidAPI-Host': 'travel-advisor.p.rapidapi.com'
            }
          });

        return data;
    }
    catch(error){
        console.log(error);
    }
} 

将以下行放入 App.js 中的 组件中时会出现问题:

places={places}
reactjs
2个回答
1
投票

yout 地图中没有出口:

在 Map.js 中 const Map 之前添加导出

export const Map = ({setCooperatives, setBounds, 坐标, 地点}) => { ………… }


0
投票

在你的 App.js 中

从 useEffect 的第二个参数中的依赖数组中删除“坐标”。

useEffect(()=>{getPlacesData(bounds.sw,bounds.ne).then((data)=>{...})},[坐标,边界]);

如果在 useEffect 或其关联函数中未使用坐标,则将其从依赖项数组中删除可以帮助避免因坐标更改而触发不必要的重新渲染。

useEffect(()=>{getPlacesData(bounds.sw,bounds.ne).then((data)=>{....})},[bounds]);

这可能有助于解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.