2016-09-13 507 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

相關問題