ReactJS抛出`TypeError:无法读取未定义的属性'latLng' [英] ReactJS throwing `TypeError: Cannot read property 'latLng' of undefined`

查看:55
本文介绍了ReactJS抛出`TypeError:无法读取未定义的属性'latLng'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个

服务器

var express = require('express');var router = express.Router();var axios = require('axios');const NodeCache = require('node-cache');const myCache = new NodeCache();让hitCount = 0;/* 获取主页.*/router.get('/', function(req, res, next) {res.render('index', { title: 'Express' });});router.get('/hello', async function(req, res, next) {const allData = myCache.get('allData');如果(!allData){命中数++;尝试 {const { 数据 } = 等待 axios.get('https://api.vesselfinder.com/vesselslist?userkey=KEY');const { 元数据,船舶} = 数据;myCache.set('allData', data, 70);console.log(data + '这是数据');res.send(数据);} 捕捉(错误){res.send(错误);控制台日志(错误);}}res.send(allData);});module.exports = 路由器;

客户

class BoatMap 扩展组件 {构造函数(道具){超级(道具);this.state = {船舶:[],过滤船舶:[],类型:'全部',船型:[],activeShipTypes: [],延迟处理器:空,地图加载:假};this.updateRequest = this.updateRequest.bind(this);}异步 componentDidMount() {this.countDownInterval = setInterval(() => {}, 500);等待 this.updateRequest();this.updateInterval = setInterval(() => {this.updateRequest();}, 60 * 1000);}异步更新请求(){const url = 'http://localhost:3001/hello';const fetchingData = 等待 fetch(url);const 船 = 等待 fetchingData.json();console.log('获取船舶', 船舶);if (JSON.stringify(ships) !== '{}') {如果(this.previousTimeStamp === null){this.previousTimeStamp = ship.reduce(function(obj, ship) {obj[ship.AIS.NAME] = ship.AIS.TIMESTAMP;返回对象;}, {});}this.setState({船舶:船舶,过滤船舶:船舶});this.props.callbackFromParent(ships);for(让船的船){if (this.previousTimeStamp !== null) {if (this.previousTimeStamp[ship.AIS.NAME] === ship.AIS.TIMESTAMP) {this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;console.log('相同的时间戳:', ship.AIS.NAME, ship.AIS.TIMESTAMP);继续;} 别的 {this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;}}让 _ship = {//发送数据 ....};const requestOptions = {方法:'POST',标头:{'内容类型':'应用程序/json'},正文:JSON.stringify(_ship)};await fetch('http://localhost:3001/users/vessles/map/latlng', requestOptions);}}}}使成为() {const noHoverOnShip = this.state.hoverOnActiveShip === null;//console.log("color", this.state.trajectoryColor);返回 (<div className="google-map"><GoogleMapReact//船舶={this.state.ships}bootstrapURLKeys={{ key: 'key' }}中心={{纬度:this.props.activeShip ?this.props.activeShip.latitude : 37.99,lng: this.props.activeShip ?this.props.activeShip.longitude:-97.31}}缩放={5.5}onGoogleApiLoaded={({ map, maps }) =>{this.map = 地图;this.maps = 地图;//我们需要这个 setState 来强制第一个 mapcontrol 渲染this.setState({ mapControlShouldRender: true, mapLoaded: true });}}>{this.state.mapLoaded ?(<div><折线地图={this.map}地图={this.maps}标记={this.state.trajectoryData}lineColor={this.state.trajectoryColor}/>

) : ('')}{/* 在此处渲染所有标记 */}{Array.isArray(this.state.filteredShips) ?(this.state.filteredShips.map((ship) => (<船舶船={船}密钥={ship.AIS.MMSI}纬度={ship.AIS.LATITUDE}lng={ship.AIS.LONGITUDE}logoMap={this.state.logoMap}logoClick={this.handleMarkerClick}logoHoverOn={this.handleMarkerHoverOnShip}logoHoverOff={this.handleMarkerHoverOffInfoWin}/>))) : ('加载中...')}</GoogleMapReact>

);}

到目前为止我做了什么:

1) 我也遇到了这个来源来帮助我解决问题,但没有运气.

2)我还咨询了这个其他来源,还有这个,但他们都没有帮助我找出可能是什么问题.

3) 我深入研究了这个问题,发现 这个来源也是.

4) 我也读过这本.但是,这些都没有帮助我解决问题.

5) 我还发现了 这个来源非常有用,但仍然没有解决方案.

感谢您指出解决此问题的正确方向.

解决方案

我发现了同样的问题 此处 与 google-map-react 相关.

查看您的代码,您的回退是纯字符串(在您的 GoogleMapReact 组件内),这会在它应该是组件时导致错误.

您的组件 GoogleMapReact 看起来也没有关闭(可能是粘贴代码时遗漏了)

我会使用 && 运算符,例如:

 { this.state.mapLoaded &&(<div><折线地图={this.map}地图={this.maps}标记={this.state.trajectoryData}lineColor={this.state.trajectoryColor}/></div>)}

对于 逻辑,我会首先尝试包装

Loading...</div>,但我猜是 google-map-react 可能不接受.如果没有,我将使用与 && 相同的方法.

I built a boat visualizer using this API. After inquiring the API I am able to obtain a json response with the vessels I am interested in and write those API information into a MongoDB database.

The problem: Everything seems to be working well, but all of a sudden the application stops working throwing a strange error below. Now I researched a lot the possible cause:

TypeError: Cannot read property 'latLng' of undefined

what I don't understand in the error is that is pointing to a property that I dopn't have : latLng and that I only see in the node modules node_modules/react/cjs/react.development.js:1149

In my code I dont have latLng but I do have latlng (notice lowercase "l") and I showed it on my code below on async updateRequest() { ... }

I also took a print screen for completeness. The output carries some strange output from a node_modules/react/cjs/react.development.js:1149 and from the part of the code interested The last part of the error is my code BoatMap.updateRequest:

server

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;

client

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>
    );
}

What I have done so far:

1) I also came across this source to help me solve the problem but no luck.

2) Also I consulted this other source, and also this one but both of them did not help me to figure out what the problem might be.

3) I dug more into the problem and found this source too.

4) I read this one too. However, neither of these has helped me fix the problem.

5) I also found this source very useful but still no solution.

Thanls for pointing to the right direction for solving this problem.

解决方案

I found the same issue here related to google-map-react.

looking at your code your fallback is plain string (inside your GoogleMapReact component), and that would be causing the error when it should be a component.

edit: your component GoogleMapReact also doesnt look closed (maybe missed from pasting the code)

I would use the && operator like:

 { this.state.mapLoaded && (
                    <div>
                        <Polyline
                            map={this.map}
                            maps={this.maps}
                            markers={this.state.trajectoryData}
                            lineColor={this.state.trajectoryColor}
                        />
                    </div>) 
}

for the <Ship> logic I would try at first wrap <div>Loading...</div>, but I would guess that google-map-react might not accept that. If it doesnt I would use the same approach with &&.

这篇关于ReactJS抛出`TypeError:无法读取未定义的属性'latLng'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆