React Native android 设置状态数组不工作

React Native android set state array not working

Android 设置状态数组无效。 React-native MapView componentWillMount 更新状态设置地图位置不起作用。请帮助我。

状态:

constructor(props) {
    super(props);
    this.state = {
        loading: '',
        mapRegion: {
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        },
        location: {
          coords: {
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }
        }
    };
  }

组件将安装

async componentWillMount() {
this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

Return视图不改变位置

<MapView style={{ width: '100%', height: '100%' }}
region={{
     latitude: this.state.location.coords.latitude,
     longitude: this.state.location.coords.longitude,
     latitudeDelta: 3,
      longitudeDelta: 3
 }}
zoomEnabled = {true}>
<MapView.Marker coordinate={this.state.location.coords} title={strings('Location.Buradasiniz')} />
<MapView.Circle center={this.state.location.coords} radius={this.state.radius} strokeColor='red' fillColor="rgba(255, 0, 0, 0.20)"/></MapView>

试试这个:

async componentWillMount() {
await this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

当你使用 async 之后你必须在某处写 await,这里是文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

或者不使用 async await 像这样尝试:

componentWillMount() {
 this.setState({
          mapRegion: {
            latitude: responseJson.latitude,
            longitude: responseJson.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          },
          location: {
            coords: {
              latitude: responseJson.latitude,
              longitude: responseJson.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }
          },
 });
}

祝你好运))