reactjs - 找不到变量 lat&lon,除了在渲染反应中到处都可以识别
问题描述
我有一个工作博览会小吃可以获取我的实时位置。它还计算从硬编码点到点数组的距离,并获得到点的最近距离。但是当我尝试用 mylat&lon 替换硬编码点时,我得到一个错误。找不到可变纬度或未定义的错误。
在整个小吃中,我可以使用 lat/lon 作为 {latitude}、{this.state.latitude} 或 {coords.latitude}。
我还尝试声明一个“const b = lat”,然后声明一个 const {b} = this.state,在这种情况下我得到 NaN。我无法让它工作。
export default class MyLocation extends React.Component {
constructor(props) {
super(props);
this.state = {
position: 'Espere ...',
timeInterval: null,
latitude: null,
longitude: null,
speed: null,
regionInicial: {
latitude: -34.911203,
longitude: -56.16737,
latitudeDelta,
longitudeDelta,
},
fill: 0,
coordsBest: {
latitude: null,
longitude: null,
speed: null,
accuracy: null,
},
coords: { latitude: null, longitude: null, speed: null, accuracy: null },
Data : [{id: "1", Point: "27.1597268, 40.6646601"},
{id: "2", Point: "11.1640393, 49.648713" },
{id: "3", Point: "26.1539253, 42.6599287"}]
};
}
idInterval = 0;
async componentDidMount() {
.....
this.startTimeInterval();
}
...
handleCenter = () => {
const {
latitude,
longitude,
latitudeDelta,
longitudeDelta,
} = this.state.location;
this.map.animateToRegion({
latitude,
longitude,
latitudeDelta,
longitudeDelta,
});
};
startTimeInterval = () => {
this.idInterval = setInterval(() => {
this.recalcularGPS();
}, 500);
};
recalcularGPS = async () => {
clearInterval(this.idInterval);
let location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true,
accuracy: Location.Accuracy.higher,
timeout: 5000,
});
const { latitude, longitude, speed, accuracy } = location.coords;
const { coordsBest } = this.state;
this.setState({
latitude: latitude,
longitude: longitude,
speed: speed,
error: null
});
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 0, distanceFilter: 1 }
await this.setState((previousState) => ({
position: accuracy.toFixed(2),
fill: accuracy.toFixed(1),
coords: location.coords,
coordsBest:
coordsBest.accuracy == null
? location.coords
: coordsBest.accuracy > accuracy
? location.coords
: coordsBest,
regionInicial: {
...previousState.regionInicial,
latitude: latitude,
longitude: longitude,
speed: speed,
},
}));
this.startTimeInterval();
const b = latitude
const c = longitude
};
stopCalcular = async () => {
clearInterval(this.idInterval);
};
componentWillUnmount() {
clearInterval(this.idInterval);
}
render() {
const { position, fill, coords, coordsBest } = this.state;
console.log('coordsBest', coordsBest);
console.log(coords.latitude, coordsBest.latitude);
const { b, c } = this.state; //probably not OK
let DistancesFromUserLocation = [];
this.state.Data.forEach((item) => {
DistancesFromUserLocation.push(
getPreciseDistance( // This is where I get the error.
{latitude: {b}, longitude: {c}}, // I need to insert here my lat & long please
item.Point
)
);
});
DistancesFromUserLocation = DistancesFromUserLocation.sort();
const distances = DistancesFromUserLocation.map((distance) => (
<Text>{distance},</Text>
));
return (
<View style={styles.container}>
{coords && (
<View style={{ paddingVertical: 10 }}>
<Text>dist0: {distances[0]}</Text> // With the hard coded coords it works
<Text>distances: {distances}</Text> // With the hard coded coords it works
<Text>Lat: {coords.latitude}</Text> // Here they work fine
<Text>Lon: {coords.longitude}</Text> // Here they work fine
</View>
)}
</View>
);
}
}
解决方案
看起来问题是由初始(少数?)渲染上的坐标纬度和经度为空引起的。
constructor(props) {
super(props);
this.state = {
...
coords: {
latitude: null, // <-- here
longitude: null, // <-- here
speed: null,
accuracy: null
},
...
};
}
您可以使用空检查来确保您没有尝试使用未定义的值计算距离。
const { Data, coords } = this.state;
const distances = Data.map(
(item) =>
!!(coords.longitude && coords.latitude) &&
getPreciseDistance(coords, item.Point)
)
// filter falsey values
.filter(Boolean)
// sort distances
.sort()
// Wrap in <Text/> for demo
.map((distance) => <Text>{distance},</Text>);
推荐阅读
- c# - 在asp net core web api中进行模型绑定时忽略XML命名空间
- php - 如何在 Shopware 6 中导入期间替换(不添加)属性?
- javascript - javascript中的API搜索仅返回过滤列表
- javascript - 除非我刷新页面,否则集成在选项卡中的手风琴不起作用
- windows-10 - FileCreateError: [Errno 24] 打开的文件太多 | Windows 10、Python、Spyder IDE
- java - POST 方法不发送数据并检索页面 301
- xml - 在 PowerShell 中将迭代 SOAP XML 行转换为列
- javascript - 请求的身份验证范围不足 javascript
- r - 如何找到总和为 colSums 和 rowSums 某些值的行?
- spring - 避免在控制台 Spring Boot 上“绑定参数”日志