如何在本机中处理承诺

问题描述 投票:0回答:1

我是react-native的初学者,目前正在尝试找到解决方法geolocation。我有一个名为region的状态,该状态已初始化为一些值。当呼叫承诺getPosition时,如果它解决了,则应重置region状态,最后它进行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;

javascript react-native geolocation react-native-maps
1个回答
0
投票

请不要在Promise中使用watchPosition。因为您只能解决1次。此外,离开时应删除监听器。

© www.soinside.com 2019 - 2024. All rights reserved.