【问题标题】:how to make componentDidMount() to finish before rendering如何使 componentDidMount() 在渲染之前完成
【发布时间】:2018-12-29 04:26:26
【问题描述】:

如何让页面在 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 最初设置在构造函数下

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我假设您的 MapViewinitialRegion 属性只能在构建 MapView 组件时设置一次,在这种情况下,您应该只在您的位置数据可用时才渲染它。所以你可以把你的渲染函数改成这样。

    render() {
      return this.state.region ? <MapView ... /> : <LoadingIndicator />;
    }
    

    并在构造函数中将state.region 初始化为null

    【讨论】:

      【解决方案2】:

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

      试试这个方法

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

      函数调用流程的规则是:

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

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 2020-11-14
        • 2018-04-21
        • 1970-01-01
        • 2018-09-19
        • 1970-01-01
        • 2020-12-16
        • 2019-12-31
        • 2021-11-21
        相关资源
        最近更新 更多