【问题标题】:How to correctly manage maps initial state in react native?如何在本机反应中正确管理地图初始状态?
【发布时间】:2020-04-02 15:01:05
【问题描述】:

我是 JS/React-native 的新手,对于如何正确管理地图的初始状态有点困惑。

我有以下组件:

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;

此代码产生错误expected ";" (16:21),这是构造函数开始的行。我猜这个问题实际上是我不能使用构造函数,除非它在一个类而不是一个函数中?

有人可以在这里指出正确的方向吗?

【问题讨论】:

  • 为什么要在功能组件中使用构造函数?检查React Fundamentals 以查看函数和类组件之间的差异。
  • @JuanMarco 我确实在问题中说“我猜问题实际上是我不能使用构造函数,除非它在类而不是函数中”。我正在寻找更多关于如何使我的代码适应类/功能组件(如接受的答案)的指导。

标签: javascript react-native jsx


【解决方案1】:

你是对的,你不能在函数组件中使用构造函数。

您可以做的是选择其中一个。 一个类组件看起来像这样:

class MyMapsComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      ...
    }
  }

  render() {
    return (
        <MapView style={{flex: 1}} Initialregion={this.state.region}/>
    );
  }
}

还有一个这样的函数组件:

function myMapsComponent({navigation}) {
  const [isLoading, setLoading] = useState(false);
  const [region, setRegion] = useState({longitude: LONGITUDE, ...});
  ...


  return (
      <MapView style={{flex: 1}} Initialregion={region}/>
  );

}

您可以了解组件(函数或类)here,以及了解useState 和其他钩子here

【讨论】:

  • 谢谢。快速提问,我的导航仍然可以与类组件一起使用吗?我注意到代码 sn-p 中的任何地方都没有提到它?
  • 在构造函数中作为props传入,让你可以在需要的地方写this.props.navigation
猜你喜欢
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多