首页 > 解决方案 > ReactJS:未处理的拒绝(TypeError)304

问题描述

我使用这个 API构建了一个小船可视化器。查询 API 后,我可以获取我感兴趣的船只的 json 响应,并将这些 API 信息写入MongoDB数据库。API请求可以每1分钟完成一次,这就是我使用const NodeCache = require('node-cache');模块绕过1分钟限制的原因。

问题:一切似乎都运行良好,但如果我手动刷新页面以查看船只的更新位置并在 1 分钟前发送请求,我会304得到Unhandled promise rejection. 所以程序不会崩溃,而是不断跳过 1 分钟将信息写入MongoDB. 这意味着由于刷新页面操作而不是每 1 分钟,我每 2 分钟获得一次职位。为什么会这样?

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

错误

API 的典型答案如下:

[  
    {  
        "AIS":{  
            "MMSI":227441980,
            "TIMESTAMP":"2017-08-11 11:17:37 UTC",
            "LATITUDE":46.1459,
            "LONGITUDE":-1.16631,
            "COURSE":360.0,
            "SPEED":0.0,
            "HEADING":511,
            "NAVSTAT":1,            
            "IMO":0,
            "NAME":"CLEMENTINE",
            "CALLSIGN":"FJVK",
            "TYPE":60,
            "A":0,
            "B":0,
            "C":0,
            "D":0,
            "DRAUGHT":0.0,
            "DESTINATION":"",
            "ETA_AIS":"00-00 00:00",
            "ETA":"",
            "SRC":"TER",
            "ZONE": "North Sea",
            "ECA": true      
        }
    }
]

下面是代码最重要的部分:

服务器

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 = {
            // .........  
        };
        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 */}
                {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}
                    />
                ))}

到目前为止我做了什么:

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

2)我也咨询了这个其他来源,还有这个来源,但他们都没有帮助我弄清楚问题可能是什么。

3)我深入研究了这个问题,也找到了这个来源

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

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

非常感谢您指出解决此问题的正确方向。

标签: javascriptnode.jsreactjs

解决方案


正如错误所说,this.state.filteredShips.map在某些情况下不是函数。这可能意味着您省略的初始状态不this.state.filteredShips具有Array. 如果您还没有过滤船只,那没关系,但您的渲染代码必须考虑到您的道具和状态的所有可能性。如果您正在调用this.state.filteredShips.map,而这不是一个函数,那么您的渲染将会失败。您应该检查它的值this.state.filteredShips并在尚未填充的情况下呈现其他内容,例如:

{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...'
}

推荐阅读