使用react-google-maps遇'lifecycle'及'google'未定义编译错误求助
解决react-google-maps中的'lifecycle'和'google'未定义错误
嘿,刚看完你的代码和报错信息,问题其实很清晰,两个小调整就能搞定:
1. 缺失lifecycle的导入
你用到了recompose库的lifecycle高阶组件,但没把它从库中导入进来。现在的导入语句只包含了compose和withProps,得把lifecycle也加上:
import { compose, withProps, lifecycle } from "recompose"
2. 错误直接使用全局google变量
react-google-maps不会把google挂载到全局作用域,而是通过props把它传递给被包装的组件。所以在componentDidMount里,你需要从this.props里取出google,而不是直接调用全局的google.maps:
componentDidMount() { const { google } = this.props; // 从props中解构出google const DirectionsService = new google.maps.DirectionsService(); // 剩下的代码保持不变,所有google.maps调用都基于这个解构出的google }
修改后的完整代码
下面是调整后的完整App.js,我把改动点标出来了:
import React, { Component } from 'react'; import './App.css'; // 改动1:添加lifecycle的导入 import { compose, withProps, lifecycle } from "recompose" import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps" const MapWithDirections = compose( withProps({ googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places", loadingElement: <div style={{ height: `100%` }} />, containerElement: <div style={{ height: `800px`, width: '800px'}} />, mapElement: <div style={{ height: `100%` }} />, }), withScriptjs, withGoogleMap, lifecycle({ componentDidMount() { // 改动2:从props中获取google const { google } = this.props; const DirectionsService = new google.maps.DirectionsService(); DirectionsService.route({ origin: new google.maps.LatLng(45.29233869999999, -70.06117489999997), destination: new google.maps.LatLng(45.3570637, -70.06257679999999), travelMode: google.maps.TravelMode.DRIVING, }, (result, status) => { if (status === google.maps.DirectionsStatus.OK) { this.setState({ directions: result, }); } else { console.error(`error fetching directions ${result}`); } }); } }) )((props) => <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }} > {props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />} </GoogleMap> ) class App extends Component { render() { return ( <div className="App"> <MapWithDirections/> </div> ); } } export default App;
额外提一句:你代码里用了this.setState,但lifecycle包装的组件默认没有初始化state,要么你可以在组件里手动初始化state,要么用recompose的withState高阶组件来管理状态,不过这是后续优化的事儿,先解决眼前的编译错误再说~
内容的提问来源于stack exchange,提问作者SomethingsGottaGive
相关产品推荐
相关产品推荐

