如何在渲染之前使componentDidMount()完成

时间:2018-12-29 04:26:27

标签: javascript reactjs react-native

如何在componentDidMount完成后呈现页面。

这里提出的所有类似问题都将得到一个与其问题特别相关的解决方案

constructor(props){
  super(props);

  this.state = {

  region: {
  latitude: 0,
  longitude: 0,
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}
  }
}

componentDidMount = () => {
   this.getMyLocation();
 };

getMyLocation = () => {

 navigator.geolocation.watchPosition(
   (position) => {

    const region = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      };
    this.setState({
      region: region
    })

   }
 );
}

render(){

<MapView
  provider={PROVIDER_GOOGLE}
  initialRegion={this.state.region}
  style = {styles.container}
  followUserLocation = {true}
  showsUserLocation = {true}

  ref="map"
  >

  </MapView>

 }

我原本以为initialregion会以当前用户位置为中心,但它会以latitude:0为中心,longtuide:0最初是在构造函数下设置的

2 个答案:

答案 0 :(得分:2)

我假设initialRegion的{​​{1}}属性只能在构造MapView组件时设置一次,在这种情况下,您应该仅在位置数据可用时进行渲染。因此您可以将渲染功能更改为类似的内容。

MapView

并在构造函数中将render() { return this.state.region ? <MapView ... /> : <LoadingIndicator />; } 初始化为state.region

答案 1 :(得分:0)

您可以将getMyLocation()移至构造函数中

尝试这种方式

constructor(props){
super(props);
this.getMyLocation();  
}

函数调用流程的规则是:

1. Reducer functions called
2. Constructor called 
3. Render () called
4. ComponentDidMount() called