【问题标题】:Fetching from API and updating the state of React comp从 API 获取并更新 React comp 的状态
【发布时间】:2017-08-31 19:08:20
【问题描述】:

我有一个表示 ESRI ArcGIS Api 底图的组件。我尝试通过从另一个 API 获取信息并使用 fetch 和 setState 更新坐标来更新地图的经度和纬度坐标。这是我的组件代码:

import React from 'react';
import { Map  } from 'react-arcgis';

class Basemap extends React.Component {

    constructor() {
        super();
        this.state = {};
    }

    componentDidMount() {
        const url = 'http://api.open-notify.org/iss-now.json';
        fetch(url)
            .then((d) => {
                this.setState({
                    center: [{d.iss_position.latitude} + ', ' + {d.iss_position.longitude}]
                });
            });
    }

    render() {
        return (
            <Map style={{ width: '100vw', height: '100vh' }} 
                    mapProperties={{ basemap: 'satellite' }} 
                    viewProperties={{ this.state.center }} />
        );
    }
}

export default Basemap;

但是,我收到此错误:

./src/components/basemap.js
Syntax error: components/basemap.js: Unexpected token, expected , (16:16)

  14 |          .then((d) => {
  15 |              this.setState({
> 16 |                  center: [{d.iss_position.latitude} + ', ' + {d.iss_position.longitude}]
     |                             ^
  17 |              });
  18 |          });
  19 |  }

我在 fetch 函数中遗漏了什么吗?

【问题讨论】:

标签: javascript api reactjs


【解决方案1】:

您从fetch 得到的响应不是您期望的 JSON 响应。

fetch('http://api.open-notify.org/iss-now.json')
  .then(response => response.json())
  .then(response => {
    this.setState({
      center: [...]
    })
})

另外,你错误地连接了结果:

如果中心是纬度,lng:

this.setState({
  center: [d.iss_position.latitude, d.iss_position.longitude]
})

this.setState({
  center: `${d.iss_position.latitude}, ${d.iss_position.longitude}`
})

this.setState({
  center: {
    latitude: d.iss_position.latitude,
    longitude: d.iss_position.longitude
  }
})

取决于响应应该是什么。

【讨论】:

  • 奇怪的是,我现在没有收到任何错误,但地图仍然缩放到默认位置并且没有采用新坐标.. 很奇怪。
  • 尝试console.log的结果,比较是否正确。
【解决方案2】:

希望对你有帮助

componentDidMount() {
    const url = 'http://api.open-notify.org/iss-now.json';
    fetch(url)
        .then((d) => {
            this.setState({
                center: [{latitude : d.iss_position.latitude} + ', ' + {longitude: d.iss_position.longitude}]
            });
        });
}

【讨论】:

    【解决方案3】:

    意外的令牌,预期的,

    Shorthand property names 存在问题。

    假设您使用的是latitudelongitude,那么它应该是

     center: [
              {latitude : d.iss_position.latitude} + ', ' + 
              {longitude: d.iss_position.longitude}
            ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2016-10-31
      • 1970-01-01
      • 2018-04-17
      相关资源
      最近更新 更多