У меня небольшие трудности с пониманием потока программы в этом родном приложении для реагирования.
Я поместил операторы console.log в приложение, чтобы попытаться понять.
Поэтому я инициализирую состояние в конструкторе на lat: 0, long: 0, err: null и markers: []. Затем в конструкторе я вызываю свой метод API, чтобы получить все местоположения и заполнить метод маркеров. Вывод с отпечатков следующий:
//Из метода рендеринга
[]
[]
[]
//Затем возвращается асинхронный метод конструктора и мы устанавливаем маркеры
{markers: [{title: "A", coordinate: {latitude: 0, longitude: 1}, description: "abc"},
{title: "B", coordinate: {latitude: 0, longitude: 1}, description: "abc"}]}
Затем я вызываю метод рендеринга, я понимаю, что это, вероятно, ужасная практика, но это была просто попытка отладки, надеясь, что тогда маркеры будут видны на карте.
Однако после этого метод рендеринга продолжает печатать [], что мне кажется очень странным, поскольку я только что установил его в конструкторе!
Any help would be appreciated.
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import MapView from 'react-native-maps';
const styles = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
});
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
class App extends Component {
constructor(props) {
super(props);
this.state = {
latitude: 0,
longitude: 0,
error: null,
markers: []
};
navigator.geolocation.getCurrentPosition(
(position) => {
this.state = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
};
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
fetch(API_URL)
.then((response) => response.json())
.then((responseJson) => {
var relevantLocations = []
for (var i = 0; i < responseJson.length; i++) {
var location = responseJson[i];
relevantLocations.push({
title: location.name,
coordinate: {latitude: location.latitude, longitude: location.longitude},
description: "test" + i
});
}
console.log("Setting state");
this.state = {
markers: relevantLocations
};
console.log(this.state);
this.render();
})
.catch((error) => {
console.error(error);
});
}
onRegionChange = (region) => {
this.setState({ region });
}
onPress = () => {
}
render() {
console.log(this.state.markers);
return (
<View style={styles.container}>
<MapView style={styles.map}
onRegionChange={this.onRegionChange}
onPress={this.onPress}
>
{this.state.markers.map(marker => {
return <MapView.Marker
key={marker}
coordinate={marker.coordinate}
title={marker.title}
description={marker.description}
/>
})}
</MapView>
</View>
);
}
}
export default App;
Как получается, что переменные, которые я устанавливаю в конструкторе, перезаписываются?
Спасибо