【发布时间】:2020-09-06 00:17:55
【问题描述】:
希望这是一个简单的解决方法,但我只是瞎了眼。我正在构建一个地理计算器,我们使用纬度和经度确定行驶距离。长话短说,我们已经为我们提供了数学函数,我们将围绕它构建应用程序。
正如标题所述,一旦输入数据并按下按钮并在第 36 行失败,我就会收到 TypeError。
import React, { useState} from 'react';
import {StyleSheet, Text, View, TextInput} from 'react-native';
import {Button} from 'react-native-elements';
import Calculations from './Calculations';
const Calculate = ({buttonTitle, lat1, lon1, lat2,lon2, distance, bearing}) => {
const [state, setState] = useState({coordinate: ''});
const updateStateObject = (vals) =>{
setState({
...state,
...vals,
});
};
return (
<View style={styles.container}>
<TextInput
placeholder = 'Enter the latitude of your starting location.'
onChangeText = {(lat1) => updateStateObject({coordinate: lat1})} //or you could do (val) => {setName(val);}
value = {state.lat1}/>
<TextInput
placeholder = 'Enter the longitude of your starting location.'
onChangeText = {(lon1) => updateStateObject({coordinate: lon1})} //or you could do (val) => {setName(val);}
value = {state.lon1}/>
<TextInput
placeholder = 'Enter the latitude of your end location.'
onChangeText = {(lat2) => updateStateObject({coordinate: lat2})} //or you could do (val) => {setName(val);}
value = {state.lat2}/>
<TextInput
placeholder = 'Enter the longitude of your end location.'
onChangeText = {(lon2) => updateStateObject({coordinate: lon2})} //or you could do (val) => {setName(val);}
value = {state.lon2}/>
<Button
title= {buttonTitle}
onPress = {() =>{
dist = Calculations.computeDistance({coordinate: lat1}, {coordinate: lon1}, {coordinate: lat2}, {coordinate: lon2});
bear = Calculations.computeBearing({coordinate: lat1}, {coordinate: lon1}, {coordinate: lat2}, {coordinate: lon2});
updateStateObject({distance: `Distance: ${dist}`});
updateStateObject({bearing: `Bearing: ${bear}`});
}} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default Calculate;
一旦调用computeDistance,它就表明应用程序失败,我将假设compute Bearing 在应用程序的当前状态下也会失败。我从一个名为 Calculations 的组件文件中导入,函数如下:
const Calculations = () =>{
...
function computeDistance(lat1, lon1, lat2, lon2) {
console.log(`p1={${lat1},${lon1}} p2={${lat2},${lon2}}`);
var R = 6371; // km (change this constant to get miles)
var dLat = ((lat2 - lat1) * Math.PI) / 180;
var dLon = ((lon2 - lon1) * Math.PI) / 180;
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return `${round(d, 3)} km`;
}
...
}
export default Calculations;
我对 JS 还很陌生,尤其是 React.js。任何指导将不胜感激!
编辑:这是我收到的错误 类型错误:_Calculations__WEBPACK_IMPORTED_MODULE_8__.default.computeDistance 不是函数
【问题讨论】:
-
您能否添加有关该错误的更多详细信息?
-
当然,我不敢相信我忘了把它扔在那里。它现在已经编辑,所以它被添加到最后。
标签: javascript reactjs