【问题标题】:Geolocation: How to pass co-ordinates between Components?地理位置:如何在组件之间传递坐标?
【发布时间】:2019-02-08 09:46:43
【问题描述】:

我正在使用 React 创建一个天气应用程序的项目。

我使用react-geolocation 提供用户位置的经纬度坐标。然后我想用这些坐标注入freeCodeCamp Weather API来自动生成用户当地的天气:

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

我创建了两个组件来实现这一点:

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

我的问题是将纬度和经度坐标从<Location /> 传递到<Main />。请在下面查看我的尝试:

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>
        );
      }
}

我相信这可能通过使用“道具”将数据从父(位置)传递到子(主)组件?

如果这不可行,我考虑使用 HTML5 Geolocation API。

所有答案将不胜感激。

【问题讨论】:

  • 不要将 react-geolocation 用作应用程序的额外包,您可以使用 html5 地理位置。
  • 我确实考虑过使用 HTML5 地理位置。如果是这样,我会在 componentDidMount() 方法中调用这样的代码吗?我可以通过 props 将坐标插入到 freeCodeCamp API 中吗?
  • 当然可以

标签: javascript reactjs


【解决方案1】:

您可以使用**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如果有语法错误,请检查

【讨论】:

  • 感谢您的回复,Sakhi - 他们非常有帮助。
  • 你的问题解决了吗?
  • 今晚我将尝试解决方案。一旦我这样做了,我会告诉你的。谢谢
  • 嗨,Sakhi。您建议的代码解决方案有效。所以,非常感谢。我的下一个任务是呈现要在我的页面上显示的所需数据。
  • 不错。我会试一试,如果有任何问题,我会重新发布进一步的问题。再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2016-05-30
  • 2020-08-05
  • 1970-01-01
  • 2022-08-22
  • 2012-01-14
  • 2021-08-04
相关资源
最近更新 更多