2016-09-13 500 views
10

构建一个小反应应用程序,将地理位置(由浏览器作为道具确定)传递给子组件。react this.props undefined或空对象

第一组分:App.jsx

import React, {Component} from 'react'; 

import DateTime from './components/dateTime/_dateTime.jsx'; 
import Weather from './components/weather/_weather.jsx'; 
import Welcome from './components/welcome/_welcome.jsx'; 

require ('../sass/index.scss'); 

export default class App extends Component { 

    constructor() { 
    super(); 
    this.state = { 
     latitude: '', 
     longitude: '' 
    }; 
    this.showPosition = this.showPosition.bind(this); 
    } 

    startApp() { 
    this.getLocation(); 
    } 

    getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(this.showPosition); 
    } else { 
     console.log("Geolocation is not supported by this browser."); 
    } 
    } 

    showPosition(position) { 
    this.setState({ 
     latitude: position.coords.latitude, 
     longitude: position.coords.longitude 
    }) 
    } 

    componentWillMount() { 
    this.startApp(); 
    } 

    render() { 
    return (
     <div className="container"> 
      <div className="header-container"> 
       <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } /> 
      <DateTime /> 
      </div> 
      <div className="welcome-container"> 
       <Welcome name="Name" /> 
      </div> 
     </div> 
    ); 
    } 
} 

此组件确定的位置,保存的纬度和经度,以状态,并传递通过道具这个信息给Weather.jsx组分,其工作,你可以看到下面的图片中:

enter image description here

而在weather.jsx组件我试图访问这些道具并获得未定义或空对象。

import React, {Component} from 'react'; 
import Fetch from 'react-fetch'; 

export default class Weather extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { 
      forecast: {}, 
      main: {}, 
      weather: {}, 
     }; 
     this.setWeather = this.setWeather.bind(this); 
    } 

    getWeather (latitude, longitude) { 
     var self = this; 

     fetch('http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c') 
      .then (function (response) { 
       if (response.status !== 200) { 
        console.log('Looks like there was a problem. Status Code: ' + response.status); 
        return; 
       } 

       response.json().then(function(data) { 
        self.setWeather(data); 
       }); 
      }) 

      .catch (function (err) { 
       console.log('Fetch Error :-S', err); 
      }); 
    } 

    setWeather (forecast) { 
     var main = forecast.main; 
     var weather = forecast.weather[0]; 

     this.setState({ 
      main: main, 
      weather: weather, 
      forecast: forecast 
     }); 
    } 

    startApp() { 
     this.getWeather(this.props.latitude, this.props.longitude); 
    } 

    componentWillMount() { 
     this.startApp(); 
    } 

    componentDidMount() { 
     // window.setInterval(function() { 
    //   this.getWeather(); 
    // }.bind(this), 1000); 
    } 

    render() { 
    return (
     <div className=""> 
      <div className="weather-data"> 
       <span className="temp">{Math.round(this.state.main.temp)}&#176;</span> 
       <h2 className="description">{this.state.weather.description}</h2> 
      </div> 
     </div> 
    ) 
    } 
} 

真的不知道是什么问题,是因为反应开发工具显示,天气组件确实有其向下传递给该组件的道具设置的位置。

编辑**解决:

所以,问题是,状态是异步设置和状态最后一次更新之前我天气组件呈现。

在render方法中对状态值的简单检查解决了问题。

render() { 

    if (this.state.latitude != '' && this.state.longitude != '') { 
     var weatherComponent = <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } /> 
    } else { 
     var weatherComponent = null; 
    } 

    return (
     <div className="container"> 
      <div className="header-container"> 
       {weatherComponent} 
      <DateTime /> 
      </div> 
      <div className="welcome-container"> 
       <Welcome name="Name" /> 
      </div> 
     </div> 
    ); 
    } 
+1

如果将初​​始化逻辑转换为'componentDidMount'而不是'componentWillMount'会怎么样。由于该元素尚未安装在DOM中,因此可能道具还没有到达组件。一旦安装,然后做这项工作。 https://facebook.github.io/react/docs/component-specs.html – lux

+0

谢谢你的建议,不幸的是没有什么区别。 但是我刚刚意识到,如果我只是在渲染函数中返回道具,它会起作用,并且我会在页面上看到渲染道具。 所以仍然不确定为什么'startApp()'函数无法访问它们。 – chinds

回答

9

我认为问题如下。 SetState异步发生。正因为如此,渲染函数在经纬度道具有数据之前触发。如果您在呈现Weather组件之前进行了一些检查,则可能不会出现此问题。这是我的意思的一个例子。

render() { 
    let myComponent; 
    if(check if props has val) { 
     myComponent = <MyComponent /> 
    } else { 
     myComponent = null 
    } 
    return (
     <div> 
      {myComponent} 
     </div> 
    ) 
} 
+0

美丽而如此简单,这个作品。不能相信我以前没有想过这个!谢谢。 – chinds

+1

是啊,这可以是一个真正的哥斯卡! –

2

你必须绑定startApp()getWeather()到组件,否则thisundefined

export default class Weather extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { 
      forecast: {}, 
      main: {}, 
      weather: {}, 
     }; 
     this.setWeather = this.setWeather.bind(this); 
     this.getWeather = this.getWeather.bind(this); 
     this.startApp = this.startApp.bind(this); 
    } 
    ... 
} 
+0

好吧,这是有道理的。有了这个改变,我现在可以使用道具。但是由于某种原因,经纬度道具会返回为空字符串,即使现在反应开发工具也会显示道具中的实际值。因此,如果我在'componentWillMount'中的'console.log(this.props)'在构造函数中获得:'Object {latitude:“”,longitude:“”}' – chinds

+1

你必须绑定'startApp()和getLocation()'在你的'App'组件中。 – QoP

+0

刚做完,仍然得到相同的空字符串 – chinds

相关问题