首页 > 解决方案 > 如何在 react-native 中处理 promise

问题描述

我是初学者,react-native目前正试图找到一种解决方法geolocation。我有一个名为的状态region,它用一些值初始化。当调用 promisegetPosition时,如果它解决了,那么它应该重置region状态,最后它对 get 进行 axios 调用markers,这意味着如果它解决了,那么markers将被称为新region状态,否则为初始状态。

但是,当我运行我的代码时,finally块似乎不起作用。我watchPosition在我的代码中使用了它将不断检测我的位置。请帮助我做错了什么

以下是我的代码:-

index.js

const getPosition = (options) => {
    return new Promise((resolve, reject) => {
        Geolocation.watchPosition(resolve, reject, options);
    })
};

const locationOptions = {enableHighAccuracy: true, timeout: 200000, maximumAge: 0};

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            region: {
                latitude: 17.399320,
                longitude: 78.521402,
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421,
            },
            markers: [],
            error: null,
        };
        this.getMarkers = this.getMarkers.bind(this)
    }

    getMarkers = () => {
        AsyncStorage.getItem('userToken').then((response) => {
            const headers = {
                'Content-Type': 'application/json',
                'x-access-token': response
            };
            session.get("/common/getIssues", {
                params: {
                    'lat': this.state.region.latitude,
                    'lng': this.state.region.longitude,
                    'rad': 5
                },
                headers: headers,
            }).then(response => {
                this.setState({markers: response.data.map(issue =>{
                    return {
                        latitude:issue.location.lat,
                        longitude:issue.location.lng
                    }
                    } )});
                console.log("data is ", this.state.markers)
            });
        });
    };

    async componentDidMount() {
        this.getMarkers()
         getPosition(locationOptions)
             .then((position) => {
                 console.log("inside")
                 this.setState({
                     region: {
                         latitude: position.coords.latitude,
                         longitude: position.coords.longitude,
                         latitudeDelta: 0.0922,
                         longitudeDelta: 0.0421,
                     }
                 })
             })
             .catch((err) => {
                 console.log("ewe",err.message)
             })
             .finally(()=>this.getMarkers())
    }

    // async componentDidUpdate(prevState) {
    //     console.log("update event is called")
    //     const radius = 10;
    //     if (this.state.region !== prevState.region) {
    //         this.setState({
    //             markers: await getIssues(this.state.region.latitude, this.state.region.longitude, radius).then(response => response.data)
    //         })
    //     }
    // }


    render() {
        return (
            <SafeAreaView>
                <ScrollView>
                    <Container>
                        <Banner name="Home"/>
                        <View style={styles.container}>
                            <MapView
                                style={styles.map}
                                provider={PROVIDER_GOOGLE} // remove if not using Google Maps
                                region={this.state.region}>
                                {
                                    (this.state.markers) && this.state.markers.map((marker, key) => (
                                        <Marker
                                            key={key}
                                            coordinate={marker}/>)
                                    )
                                }
                            </MapView>
                        </View>
                        <View style={{flex: 1}}>
                            <Text style={styles.text}>Filter By Category</Text>
                            <ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>
                                {icons.map((object, i) => (
                                    <Button key={i} style={styles.circleShapeView}>
                                        <Ionicon color="#fff" size={35} name={object.icon}/>
                                        <Text style={styles.iconName}>{object.name}</Text>
                                    </Button>
                                ))}
                            </ScrollView>
                        </View>
                    </Container>
                </ScrollView>
            </SafeAreaView>
        );
    }
}

export default Home;

标签: javascriptreact-nativegeolocationreact-native-maps

解决方案


请不要watchPosition与 Promise 一起使用。因为你只能解决1次。此外,您应该在离开时移除您的听众。

componentDidMount() {
    this.watchId = Geolocation.watchPosition(this.handleLocation, error => {}, {});
}

componentWillUnmount() {
    Geolocation.clearWatch(this.watchId);
}

handleLocation(location) {
    // Do your work here
}

推荐阅读