javascript - ReactJS抛出`TypeError:无法读取未定义的属性'latLng'
问题描述
我使用这个API构建了一个小船可视化器。查询 API 后,我可以获取我感兴趣的船只的 json 响应,并将这些 API 信息写入 MongoDB 数据库。
问题:一切似乎都运行良好,但应用程序突然停止工作,并在下面抛出一个奇怪的错误。现在我研究了很多可能的原因:
TypeError: Cannot read property 'latLng' of undefined
我在错误中不明白的是它指向一个我没有的属性:latLng
而且我只在节点模块中看到node_modules/react/cjs/react.development.js:1149
在我的代码中我没有,latLng
但我有latlng
(注意小写“l”),我在下面的代码中展示了它async updateRequest() { ... }
为了完整起见,我还打印了一个屏幕。输出带有一些来自 anode_modules/react/cjs/react.development.js:1149
和感兴趣的代码部分的奇怪输出错误的最后一部分是我的代码BoatMap.updateRequest
:
服务器
var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();
let hitCount = 0;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/hello', async function(req, res, next) {
const allData = myCache.get('allData');
if (!allData) {
hitCount++;
try {
const { data } = await axios.get(
'https://api.vesselfinder.com/vesselslist?userkey=KEY'
);
const { metaData, ships } = data;
myCache.set('allData', data, 70);
console.log(data + 'This is the data');
res.send(data);
} catch (error) {
res.send(error);
console.log(error);
}
}
res.send(allData);
});
module.exports = router;
客户
class BoatMap extends Component {
constructor(props) {
super(props);
this.state = {
ships: [],
filteredShips: [],
type: 'All',
shipTypes: [],
activeShipTypes: [],
delayHandler: null,
mapLoaded: false
};
this.updateRequest = this.updateRequest.bind(this);
}
async componentDidMount() {
this.countDownInterval = setInterval(() => {
}, 500);
await this.updateRequest();
this.updateInterval = setInterval(() => {
this.updateRequest();
}, 60 * 1000);
}
async updateRequest() {
const url = 'http://localhost:3001/hello';
const fetchingData = await fetch(url);
const ships = await fetchingData.json();
console.log('fetched ships', ships);
if (JSON.stringify(ships) !== '{}') {
if (this.previousTimeStamp === null) {
this.previousTimeStamp = ships.reduce(function(obj, ship) {
obj[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
return obj;
}, {});
}
this.setState({
ships: ships,
filteredShips: ships
});
this.props.callbackFromParent(ships);
for (let ship of ships) {
if (this.previousTimeStamp !== null) {
if (this.previousTimeStamp[ship.AIS.NAME] === ship.AIS.TIMESTAMP) {
this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
console.log('Same timestamp: ', ship.AIS.NAME, ship.AIS.TIMESTAMP);
continue;
} else {
this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
}
}
let _ship = {
// ships data ....
};
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_ship)
};
await fetch('http://localhost:3001/users/vessles/map/latlng', requestOptions);
}
}
}
}
render() {
const noHoverOnShip = this.state.hoverOnActiveShip === null;
// console.log("color", this.state.trajectoryColor);
return (
<div className="google-map">
<GoogleMapReact
// ships={this.state.ships}
bootstrapURLKeys={{ key: 'key' }}
center={{
lat: this.props.activeShip ? this.props.activeShip.latitude : 37.99,
lng: this.props.activeShip ? this.props.activeShip.longitude : -97.31
}}
zoom={5.5}
onGoogleApiLoaded={({ map, maps }) => {
this.map = map;
this.maps = maps;
// we need this setState to force the first mapcontrol render
this.setState({ mapControlShouldRender: true, mapLoaded: true });
}}
>
{this.state.mapLoaded ? (
<div>
<Polyline
map={this.map}
maps={this.maps}
markers={this.state.trajectoryData}
lineColor={this.state.trajectoryColor}
/>
</div>
) : (
''
)}
{/* Rendering all the markers here */}
{Array.isArray(this.state.filteredShips) ? (
this.state.filteredShips.map((ship) => (
<Ship
ship={ship}
key={ship.AIS.MMSI}
lat={ship.AIS.LATITUDE}
lng={ship.AIS.LONGITUDE}
logoMap={this.state.logoMap}
logoClick={this.handleMarkerClick}
logoHoverOn={this.handleMarkerHoverOnShip}
logoHoverOff={this.handleMarkerHoverOffInfoWin}
/>
))
) : (
'Loading...'
)}
</GoogleMapReact>
</div>
);
}
到目前为止我做了什么:
1)我也遇到了这个来源来帮助我解决问题,但没有运气。
2)我也咨询了这个其他来源,还有这个来源,但他们都没有帮助我弄清楚问题可能是什么。
3)我深入研究了这个问题,也找到了这个来源。
4)我也读过这个。但是,这些都没有帮助我解决问题。
5)我也发现这个来源非常有用,但仍然没有解决方案。
感谢您指出解决此问题的正确方向。
解决方案
我在这里发现了与 google-map-react 相关的相同问题。
查看您的代码,您的后备是纯字符串(在您的GoogleMapReact
组件内),当它应该是一个组件时,这会导致错误。
编辑:您的组件GoogleMapReact
看起来也没有关闭(可能是粘贴代码时遗漏了)
我会使用这样的&&
运算符:
{ this.state.mapLoaded && (
<div>
<Polyline
map={this.map}
maps={this.maps}
markers={this.state.trajectoryData}
lineColor={this.state.trajectoryColor}
/>
</div>)
}
对于<Ship>
我首先会尝试的逻辑 wrap <div>Loading...</div>
,但我猜想 google-map-react 可能不会接受。如果不是,我会使用与&&
.
推荐阅读
- java - 如果它们包含类似的比较,为什么 Java 会跳过 if 子句?
- c# - 如何在 C# 中使用 Utils.FormIsOpen
- c - 有没有办法在POSIX中原子地增加一个信号量并减少另一个信号量?
- javascript - 如何使复制按钮提醒许多按钮?
- nginx - Nginx - try_files 正则表达式
- python - 我可以识别小写和大写字母并将它们放入字典中。我需要将大写和小写值连接在一起
- vb.net - 当 LINQ IEnumerable 的返回为空时,如何不添加到列表中?
- android - Flutter:DropDownButton列表从一开始就没有显示
- python-3.x - 如何在不使用 cov 和 corr 的情况下计算 Python 中的协方差和相关性?
- oop - 非抽象类的非空方法和抽象方法的抽象方法的好处?