如何使用setState

时间:2018-09-05 13:50:30

标签: json api react-native react-native-maps

我正在尝试将http://api.postcodes.io/postcodes/NW10AP的纬度和经度结果存储到我的Marker.coordinate状态,以便我的地图可以呈现新的标记。

真的很想办法做到这一点,将不胜感激! :)

请查看下面的代码

    import React from 'react';
    import { MapView } from 'expo';
    import { Marker } from 'react-native-maps';
    import {Image, ActivityIndicator, View, Text, FlatList} from 'react-native';



    export default class App extends React.Component {

      state = {
        region: {
          latitude: 51.5074,
          longitude: 0.1278,
          latitudeDelta: 0.1,
          longitudeDelta: 0.1
        },
        marker: {
            title: 'Hello there',
            coordinate: {latitude: 51.5074, longitude: 0.1278}
            }
        }



      onRegionChange = (region) => {
        this.setState({region});
        // console.log(region)
      }

           componentDidMount(){
        return fetch('http://api.postcodes.io/postcodes/sw151pf')
          .then((response) => response.json())
          .then((responseJson) => {
            let marker = {...this.state.marker}
            marker.coordinate.latitude = responseJson.result.latitude;
            marker.coordinate.longitude = responseJson.result.longitude;


            this.setState({
              marker
            }, function(){

            });

          })
          .catch((error) =>{
            console.error(error);
          });
      }




      render() {

        return (

          <MapView
            style={{ flex: 1 }}
            region={this.state.region}
            onRegionChange={this.onRegionChange}

          >

            <Marker
              coordinate={this.state.marker.coordinate}
              title={this.state.marker.title}
            />

          </MapView>

        )
      }
    }

1 个答案:

答案 0 :(得分:1)

在获取呼叫中,您可以使用以下内容。

let marker = Object.assign({},this.state.marker)
marker.coordinate.latitude = responseJson.result.latitude;
marker.coordinate.longitude = responseJson.result.longitude;

this.setState({ marker });

如果这不起作用,请使用immutability-helper

https://github.com/kolodny/immutability-helper/blob/master/README.md

您的代码应如下所示:

import update from 'immutability-helper';

用于获取呼叫。

const newMarker = update(this.state.marker,{
  coordinate: {
    latitude: {$set:responseJson.result.latitude},
    longitude: {$set: responseJson.result.longitude}
  }
})

this.setState({ marker:newMarker });

完整代码:

componentDidMount() {
    return fetch('http://api.postcodes.io/postcodes/sw151pf')
      .then((response) => response.json())
      .then((responseJson) => {

        const newMarker = update(this.state.marker,{
          coordinate: {
            latitude: {$set:responseJson.result.latitude},
            longitude: {$set: responseJson.result.longitude}
          }
        })
        this.setState({ marker:newMarker });

      })
      .catch((error) => {
        console.error(error);
      });
  }