[英]React Js: Type Error React-Leaflet When i used first cordinate for marker
当我使用折线坐标的第一个和最后一个索引显示在标记上时,我试图使用坐标在 React-Leaflet 地图上显示标记,并且我一直收到类型错误,我不知道错误在哪里。 我还尝试创建特定的开始和结束坐标,但我一直遇到相同的错误如何解决这个问题。 这是我的代码。
import React, { Component } from "react";
import config from "../Main";
import { Map, TileLayer, Polyline, Marker, Popup } from "react-leaflet";
import { withRouter } from "react-router-dom";
class Mapp1 extends Component {
constructor(props) {
super(props);
this.state = {
mapa: [],
center: [52.3197, 21.0152],
cords: [],
start: [],
end:[],
};
}
async componentDidMount() {
let authToken = localStorage.getItem("Token");
try {
const res = await fetch(
`${config.apiUrl.carmapN}${this.props.match.params.id}/`,
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + JSON.parse(authToken)
}
}
);
const mapa = await res.json();
// console.log(mapa);
this.setState({
mapa,
cords: mapa.coordinates,
//start: mapa.coordinates[0],
//end: mapa.coordinates[-1]
});
} catch (e) {
console.log(e);
}
}
render() {
const { mapa } = this.state;
const { cords } = this.state;
if (mapa === null) return <p>Loading ....</p>;
const center = this.state.center;
console.log("StarPint ", this.state.start);
return (
<div className="container" style={{ marginTop: "20px" }}>
<div className="headerr">
<h2 style={{ marginTop: "20px" }} className="font-weight-bolder">
MAPS
</h2>
<div className="row" style={{ marginTop: "30px" }}>
<div className="col-sm-5">
<Map
center={center}
zoom={9}
style={{ width: "520px", height: "480px" }}
>
// This is for startpoint marker and its showing error
<Marker position={cords[0]} color="red">
<Popup>
This is your Starting <br /> point at 8:45
</Popup>
</Marker>
// This is for endpoint marker and its showing error
<Marker position={cords[-1]} color="green">
<Popup>
{mapa.endPlace} <br /> point at {mapa.endTime}
</Popup>
</Marker>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<Polyline
positions={cords}
color={"red"}
lineJoin={"round"}
lineCap={"round"}
opacity={1}
weight={5}
// dashArray={"9"}
// dashOffset={"3"}
fill={false}
stroke={true}
fillRule={"evenodd"}
onMouseOver={e => e.target.openPopup()}
onMouseOut={e => e.target.closePopup()}
></Polyline>
</Map>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(Mapp1);
您的检查 if (mapa === null) 总是返回 false,因为 mapa 被初始化为 [] not null。 所以初始渲染采用空数组。 将其修改为 if (mapa.length === 0) 或 if(!mapa.length)。
让我知道这是否解决了问题。 如果确实如此,我建议您从 ecma 文档或任何可信赖的在线资源(如 mdn)中引用双重相等强制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.