reactjs - 点击地图后刷新调用api
问题描述
我从反应开始,我想制作一个系统,当我点击由模块“React-Leaflet”生成的地图来修改我的标记时。单击此按钮后,我想调用 Api 以将数据刷新到我的组件 Weather。我能怎么做 ?你能帮我吗 ?
这是我的组件 Weather :
import './Meteo.css';
import React, { Component } from 'react';
import axios from 'axios';
import { getLat, getLng } from '../../Store.js';
export default class Meteo extends Component {
constructor(props) {
super(props);
this.state = {
temp: "",
pressure: "",
humidity: "",
temp_min: "",
temp_max: "",
}
}
componentDidMount() {
const lat = getLat();
const lng = getLng();
axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${APIKEY}`)
.then(res => {
const meteo = res.data;
console.log("Meteo" + meteo);
this.setState({
temp: meteo.main.temp,
pressure: meteo.main.pressure,
humidity: meteo.main.humidity,
temp_min: meteo.main.temp_min,
temp_max: meteo.main.temp_max,
});
})
}
render() {
return (
<p>Meteo</p>
)
};
}
这是我的组件地图:
import './Map.css';
import React, { Component } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import L from "leaflet";
import { getLat, getLng, setLat, setLng } from '../../Store.js';
const customMarker = new L.icon({
iconUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png",
iconSize: [25, 41],
iconAnchor: [13, 0]
});
export default class MapLeaflet extends Component {
constructor(props) {
super(props);
this.state = {
lat: getLat(),
lng: getLng(),
}
}
updateMarker = (e) => {
setLat(e.latlng.lat);
setLng(e.latlng.lng);
this.setState({
lat: e.latlng.lat,
lng: e.latlng.lng,
});
}
render() {
const position = [this.state.lat, this.state.lng]
return (
<div className="map">
<Map center={position} zoom={13} className="map" onClick={this.updateMarker} >
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position} icon={customMarker}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</Map>
</div>
)
}
}
这是我的商店:
const coord = {
lat: 51.505,
lng: -0.09
}
export function getLat(){
return coord.lat;
}
export function getLng(){
return coord.lng;
}
export function setLat(lat){
coord.lat = lat;
}
export function setLng(lng){
coord.lng = lng;
}
解决方案
其中一种方法是您应该将坐标和数据移动到父组件状态,然后将它们作为道具传递给 MapLeaflet 和 Meteo 组件。创建将在标记位置更新时更新坐标然后获取数据的新方法。这是一个示例https://codesandbox.io/s/x3p2kwnzvz - 它没有地图,我使用 Math.random 生成数据
推荐阅读
- python - HomeAssistant 取消 AppDaemon 中的回调
- php - PHPUnit错误:找不到类'ClassName'
- c# - 如何在 C# 中添加带字符串的整数并制作类似 Json 的格式
- python - 如何绘制遍历多个键的字典DataFrame?
- python - 根据熊猫列中唯一数量的元素删除行
- javascript - 将 IndexOf 与日期和谷歌表格一起使用
- python - print(file.read()) 的用途是什么
- amazon-ec2 - AWS EC2 实例自托管 webapi 安装 ssl 证书
- c# - 如何仅在 C# 编辑器 IntelliSense 中隐藏公共类?
- ios - 在 Xcode 11 中添加对本地 swift 包的依赖