简体   繁体   中英

React.js TypeError: Module not a function

Hopefully this is an easy fix and I'm just blind. I'm building a geo calculator where we determine distance traveled using latitude and longitude. Long story short, the functions for the math has been provided for us and we are to build the app around that.

As the title states I receive a TypeError once data is put in and a button is pressed and fails on line 36.

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;

It points to the app failing once computeDistance is called and I'm going to assume compute Bearing will also fail at the current state of the app. I am importing from a component file called Calculations and the functions are like this:

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;

I'm fairly new to JS and especially new to React.js. Any guidance would be appreciated!

Edit: this is the error I receive TypeError: _Calculations__WEBPACK_IMPORTED_MODULE_8__.default.computeDistance is not a function

You are declaring Calculations as a function and you cannot access anything within. If you want to call the function as it is in your code you can do this to 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`;
}

Calculations.computeDistance = computeDistance;

export default Calculations;

Thank you everyone for your help. what I ended up doing was essentially getting rid of Calculation as a function in its entirety and having the functions on the page by itself. Then exporting each function that I needed for Calculate importing them individually using

import {computeDistance, computeBearing} from './Calculations';

The other ways suggested were incredibly helpful in helping me think through this and simplifying my code!

Seems like you have imported Calculations in the wrong way.

You should be doing: import { Calculations} from './Calculations';

By importing Calculations with brackets, React will know that you are taking the function instead of the whole thing. In this way, you can export the function out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM