【问题标题】:React Native set flow of functions callsReact Native 设置函数调用流
【发布时间】:2020-11-03 11:16:14
【问题描述】:

这段代码是我写的

componentDidMount(){
    
    Geolocation.getCurrentPosition(info => {
        console.log(info.coords.latitude + "    " + info.coords.longitude)
        this.setState({coords: {latitude: info.coords.latitude, longitude: info.coords.longitude, latitudeDelta: this.LATITUDE_DELTA, longitudeDelta: this.LONGITUDE_DELTA}})
    }, error => Alert.alert('Error', JSON.stringify(error)),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
      
    console.log(this.state.coords.latitude + "    " + this.state.coords.longitude);

    region = getapi(this.state.coords.latitude, this.state.coords.longitude)
    this.setState({region})
    console.log("TEMP: " + region);
    hot = getHotBarb(this.state.region)
    this.setState({hot})
    rated = getRatedBarb(this.state.region)
    this.setState({rated})
    offer = getOfferBarb(this.state.region)
    this.setState({offer})

    this.setState({loading: false})

}

但在日志控制台上,我首先看到 this.state.coords.latitude + " " + this.state.coords.longitude 的日志(未定义)和 getCurrentPosition 调用中的日志(正确)。 问题是我不能调用函数 getapi 因为 this.state.coords.latitude, this.state.coords.longitude 结果未定义 我需要先设置this.state.coords.latitudethis.state.coords.longitude,然后调用componentDidMount()中的其他函数。

如何在 getCurrentPosition 函数上获取 setState 以在其他函数之前调用?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    试试这个方法

    callApi(){
    
        console.log(this.state.coords.latitude + "    " + this.state.coords.longitude);
    
        region = getapi(this.state.coords.latitude, this.state.coords.longitude)
        this.setState({region})
        console.log("TEMP: " + region);
        hot = getHotBarb(this.state.region)
        this.setState({hot})
        rated = getRatedBarb(this.state.region)
        this.setState({rated})
        offer = getOfferBarb(this.state.region)
        this.setState({offer})
    
        this.setState({loading: false})
    }
    
    
    getCurrentPosition(){
    
        Geolocation.getCurrentPosition(info => {
            console.log(info.coords.latitude + "    " + info.coords.longitude);
    
            this.setState({coords: {latitude: info.coords.latitude, longitude: info.coords.longitude, latitudeDelta: this.LATITUDE_DELTA, longitudeDelta: this.LONGITUDE_DELTA}},
        () => this.callApi();  // call api here
        )
    
        }, error => Alert.alert('Error', JSON.stringify(error)),
        {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
    }
    
    
    componentDidMount(){    
        this.getCurrentPosition();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多