【问题标题】:Using props in react在反应中使用道具
【发布时间】:2017-03-24 18:18:05
【问题描述】:

我正在使用来自 api 的数据构建一个应用程序,我想在应用程序中包含用户的纬度和经度。

我的应用位于两个文件中:app.jsmain.js

app.js 我这样渲染组件:

render(<Main source="https://api.darksky.net/forecast/apikey/latitude,longitude?units=auto"/>, document.getElementById('app'));

纬度和经度目前在组件源中被硬编码,我想让这些动态。

在我的main.js 中,组件使用这样的 api:

componentDidMount() {
 this.serverRequest = $.get(this.props.source, function (result) {
  this.setState({
    daily: result.daily.data,
    hourly: result.hourly.data
  });
 }.bind(this));
}

我能够使用 HTML 地理位置获取用户位置 - 我想我应该将其存储在构造函数或 componentWillMount 中,但我需要一种方法将变量发送到主组件源中的 app.js 文件中 - 我我想我应该使用像源这样的道具,但我不知道如何

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    将经度和纬度作为道具传递到组件中并在组件内部组装 URL 可能是一个好方法:

    render(<Main longitude={longitude} latitude={latitude} />, document.getElementById('app'));
    

    componentDidMount() {
        const url = `https://api.darksky.net/forecast/apikey/${this.props.latitude},${this.props.longitude}?units=auto`;
        this.serverRequest = $.get(url, function (result) {
            this.setState({
                daily: result.daily.data,
                hourly: result.hourly.data
            });
        }.bind(this));
    }
    

    【讨论】:

    • 你需要先获取坐标,这是一个异步动作。
    • 这行得通,谢谢! :) 是否可以将地理位置放置在 componentDidMount 中以在这里也获取纬度和经度?
    • 当然,您可以简单地在组件的componentDidMount 中进行调用,然后启动地理定位回调的API 调用。
    【解决方案2】:

    由于 HTML 地理位置是异步的,render() 调用可以进入地理位置成功回调:

    if (navigator.geolocation){
    
      function success(position) {
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        ReactDOM.render(
            <Main lat={ latitude } lon={ longitude } />, document.getElementById('container')
        );
      };
    
      function error() {
        console.log( 'geolocation error' )
      };
    
    
      navigator.geolocation.getCurrentPosition(success, error);
    
    }
    

    https://jsfiddle.net/69z2wepo/62204/

    更高级的示例是执行地理定位并将坐标传递给包装组件的高阶组件。然后,包装的组件应检查 componentWillReceiveProps 方法中的坐标,并在道具非空时执行 AJAX 请求:

    var GeoComponent = Component => React.createClass({
        getInitialState(){
            return {
                lat : null, 
                lon : null
            }
        },
    
        componentDidMount(){
            navigator.geolocation.getCurrentPosition(this.setCoordinates, err => console.log( err ));
        },
    
        setCoordinates( position ){
            this.setState({
                lat : position.coords.latitude,
                lon : position.coords.longitude
            })
        },
    
        render(){
            return <Component lat={ this.state.lat } lon={ this.state.lon } { ...this.props } />;
        }
    });
    
    var Main = React.createClass({
        componentWillReceiveProps( nextProps ){
            if( nextProps.lat && nextProps.lon ){
                console.log( 'received coords!' );
                /*
                  this.serverRequest = $.get(this.props.source, function (result) {
                  this.setState({
                  daily: result.daily.data,
                  hourly: result.hourly.data
                  });
                  }.bind(this));
                */
            }
        },
    
        render(){
            return <div>Latitude: { this.props.lat }, Longitude: { this.props.lon }</div>;
        }
    
    });
    
    
    ReactDOM.render(
        React.createElement(GeoComponent(Main )),
        document.getElementById('container')
    );
    

    https://jsfiddle.net/69z2wepo/62205/

    【讨论】:

    • 感谢您的回复。你是对的,我需要将渲染方法放在回调中以使其工作。但是我觉得感觉有点慢,因为我必须等待地理位置触发 - 但我想这是唯一的方法?
    【解决方案3】:

    如果我没记错的话,那么您想要实现的是访问app.js 中的地理位置信息,不是吗?那么为什么不直接在app.js 中获取用户地理位置并将其传递给Main?代码类似于

    app.js

    let geo = null;
    navigator.geolocation.getCurrentPosition(function(pos) {
      geo = pos;
    
      render(<Main source={`https://api.darksky.net/forecast/apikey/${geo.coords.latitude},${geo.coords.longitude}?units=auto`}/>, document.getElementById('app'));
    
      // Below use user's geolocation info as you wish
    });
    

    或者,如果您想在获取用户的地理位置信息之前呈现一些占位符,那么您可以让 Main 组件完成大部分事情,并将回调传递给 Main 以将地理位置信息更新到 app.js

    app.js

    render(<Main updateGeolocation={geo => { /* do stuffs with geo */ }} />, document.getElementById('app'));
    

    main.js

    componentDidMount() {
     navigator.geolocation.getCurrentPosition(function(pos) {
      this.serverRequest = $.get(`https://api.darksky.net/forecast/apikey/${pos.coords.latitude},${pos.coords.longitude}?units=auto`, function (result) {
       this.setState({
         daily: result.daily.data,
         hourly: result.hourly.data
       });
      }.bind(this));
    
      this.props.updateGeolocation(pos);
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-07
      • 1970-01-01
      • 2016-08-29
      • 2022-01-16
      • 1970-01-01
      • 2018-11-25
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多