使用google-map-react时出现Element type is invalid运行错误如何解决
错误解决方案
该运行时错误的核心原因是组件导入方式不符合依赖的导出规则,导致渲染时拿到的组件值为undefined,具体修改步骤如下:
- 修正React导入语句
React为默认导出,无需放入花括号中,将首行代码修改为:import React, { useState, useEffect } from 'react'; - 修正
google-map-react导入语句google-map-react的核心地图组件是默认导出,不是命名导出,你之前使用花括号的命名导入方式会拿到undefined,将第二行代码修改为:import GoogleMapReact from 'google-map-react'; - 依赖完整性检查(可选)
如果修改导入后仍存在报错,可先检查是否已安装该依赖,未安装执行以下命令即可:npm i google-map-react # 或者yarn安装 yarn add google-map-react
修正后完整代码
import React, { useState, useEffect } from 'react'; import GoogleMapReact from 'google-map-react'; import styles from './Location.module.scss'; import pinstyles from './TheMap.module.scss'; import { useIntl } from 'react-intl'; /* This file has the actual with the coordinates passed to it */ const TheMap = (props) => { // for holding the API key and language const bootstrapURLKeys = { //should this be french? key: process.env.NEXT_PUBLIC_API_KEY, language: 'en', }; // To do with the language of the map const { formatMessage: f } = useIntl(); return ( <div className={styles.main}> <div className={styles.heading}> {f({ id: 'location' })} </div> <div className={styles.mapContainer}> <GoogleMapReact bootstrapURLKeys={bootstrapURLKeys} defaultZoom={props.zoom} center={props.center} yesIWantToUseGoogleMapApiInternals options={{ fullscreenControl: false }} > <Marker lat={props.lat} lng={props.lng} /> </GoogleMapReact> </div> {/* Adding the address to the bottom of the map */} {props.location[1].address} {props.location[1].postalCode} </div> ); }; const Marker = (props) => { return ( <> <div className={pinstyles.pin}></div> <div className={pinstyles.pulse}></div> </> ); }; export default TheMap;
内容的提问来源于stack exchange,提问作者Siddu Palaparthi
相关产品推荐
相关产品推荐

