从API获取并更新React comp的状态 [英] Fetching from API and updating the state of React comp
本文介绍了从API获取并更新React comp的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代表ESRI ArcGIS Api底图的组件.我尝试通过从另一个API获取信息并使用fetch和setState更新坐标来更新地图的经度和纬度坐标.这是我的组件代码:
I have a component that represents a basemap from ESRI ArcGIS Api. I try to update the longitute and latitude coordinates of the map by fetching info from another API and updating the coords using fetch and setState. This is my component code:
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 | }
我在提取功能中缺少什么吗?
Am I missing something in the fetch function?
推荐答案
您从fetch
获得的响应不是您期望的JSON响应.
The response you are getting from fetch
is not the JSON response you are expecting.
fetch('http://api.open-notify.org/iss-now.json')
.then(response => response.json())
.then(response => {
this.setState({
center: [...]
})
})
此外,您错误地连接了结果:
Also, you are concatenating the result wrongly:
如果中心是lat,则表示:
If center is lat, 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
}
})
取决于响应的内容.
这篇关于从API获取并更新React comp的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文