2016-09-13 9 views
10

ジオロケーション(ブラウザで子コンポーネントに小道具として決定)を渡す小さな反応アプリを構築します。react this.props undefinedまたは空のオブジェクト

第一成分:App.jsxこのコンポーネントは、位置を決定する状態に緯度と経度を節約し、あなたができるように働いているWeather.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> 
    ); 
    } 
} 

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

問題が反応するのdevのツールとしては何か本当にわからないが、天気コンポーネントが実際にそのコンポーネントに渡され小道具に設定された場所を持っていないことを示します。

編集**解決:

だから、問題は状態が非同期に設定されているということであったと状態が更新される前に、私の気象要素が描画されたこと。

レンダリングメソッド中にstate内の値を簡単にチェックすることで問題が解決されました。

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

初期化ロジックを 'componentWillMount'ではなく' componentDidMount'に移行するとどうなりますか?要素がまだ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: ""、経度: ""} ' – chinds

+1

に' startApp() 'をバインドする必要があります。あなたの 'App'コンポーネントでもgetLocation()を呼び出します。 – QoP

+0

ちょうどそれをしても、同じ空の文字列を得る – chinds

関連する問題