首页 > 解决方案 > Geolocation: How to pass co-ordinates between Components?

问题描述

I am working on a project using React to create a weather app.

I am using react-geolocation to provide the latitude and longitude co-ordinates of the user's location. I then want to use these co-ordinates to inject into the freeCodeCamp Weather API to automatically generate the user's local weather:

e.g. https://fcc-weather-api.glitch.me/api/current?lat={insert lat}&lon{insert lon}

I have created two components to achieve this:

  1. <Main />
  2. <Location />

My issue is in passing the latitude and longitude co-ordinates from <Location /> into <Main />. Please see my attempt below:

class Location extends Component {
  render() {
    return(
      <div>
        <Geolocation
    render={({
      fetchingPosition,
      position: { coords: { latitude, longitude } = {} } = {},
      error,
      getCurrentPosition
    }) =>
      <div>
        {error &&
          <div>
            {error.message}
          </div>}
        { latitude && longitude && <Main latitude={latitude} longitude={longitude} />}
      </div>}
        />
      </div>
    )
  }
}


class Main extends Component {
    constructor(props) {
      super(props)
      this.state = {
        lat: null,
        lon: null
      }
    } 
    componentDidMount() {
      axios.get(`https://fcc-weather-api.glitch.me/api/current?lat={this.props.latitude}&lon={this.props.longitude}`)
      .then(res => {
        console.log(res.data);
        // set state with response data e.g. this.setState()
      })
    } 
      render() {
        return (
          <div>
            // Weather Data 
          </div>
        );
      }
}

I believe this may be possible through the use of "props" to pass data from Parent (Location) to Child (Main) Component?

If this is not possible, I thought about using HTML5 Geolocation API.

All answers will be appreciated.

标签: javascriptreactjs

解决方案


您可以使用获取当前位置,**Html5 Geolocation API**并且您需要向您的应用程序添加额外的包以增加应用程序大小。

这是示例:

class Main extends Component {
constructor(props) {
  super(props)
  this.state = {
    lat: null,
    lon: null
  }
    } 
    componentDidMount() {
     if (navigator.geolocation)
      navigator.geolocation.getCurrentPosition(this.showPosition, this.showError, options);

}
  showPosition = (position) => {

        axios.get(`https://fcc-weather-api.glitch.me/api/current?lat={position.coords.latitude}&lon={position.coords.longitude}`)
      .then(res => {
        console.log(res.data);
        // set state with response data e.g. this.setState()
      })
    }
      }
});
}

  showError = (error) => {
    console.warn("Error", error);
  }

  render() {
    return (
      <div>
        // Weather Data 
      </div>
    );
  }
}

PS检查语法错误是否有


推荐阅读