Cutter :
I'm new to JS/React-native and I'm a bit confused as to how I can correctly manage a maps initial state.
I've got the following component:
import React from 'react';
import { StyleSheet, Text, View, Dimensions} from 'react-native';
import Colors from '../constants/Colors'
import MapView from 'react-native-maps'
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 53.2274476;
const LONGITUDE = -0.5474525;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
function myMapsComponent({navigation}) {
constructor(props) {
super(props);
this.state = {
isLoading: true,
location: null,
errorMessage: null,
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
}
}
return (
<MapView style={{flex: 1}} Initialregion={this.state.region}/>
);
}
const styles = StyleSheet.create({
});
export default myMapsComponent;
This code produces the error expected ";" (16:21)
Which is the line where the constructor starts. I'm guessing that the problem is actually that I can't use a constructor unless it's within a class rather than a function?
Can someone point me in the right direction here?
Kraylog :
You are correct, you can't use a constructor in a function component.
What you can do is choose the one or the other. A class component would look like this:
class MyMapsComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
...
}
}
render() {
return (
<MapView style={{flex: 1}} Initialregion={this.state.region}/>
);
}
}
And a function component like this:
function myMapsComponent({navigation}) {
const [isLoading, setLoading] = useState(false);
const [region, setRegion] = useState({longitude: LONGITUDE, ...});
...
return (
<MapView style={{flex: 1}} Initialregion={region}/>
);
}
You can learn about components (function or class) here, and about useState
and other hooks here
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=391113&siteId=1