[英]How to correctly manage maps initial state in react native?
I'm new to JS/React-native and I'm a bit confused as to how I can correctly manage a maps initial state.我是 JS/React-native 的新手,我对如何正确管理地图初始状态感到有些困惑。
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)
此代码产生
expected ";" (16:21)
的错误expected ";" (16:21)
expected ";" (16:21)
Which is the line where the constructor starts. expected ";" (16:21)
这是构造函数开始的那一行。 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?有人可以在这里指出我正确的方向吗?
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您可以了解组件(函数或类)这里,和大约
useState
等挂钩这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.