構建一個小反應應用程序,將地理位置(由瀏覽器作爲道具確定)傳遞給子組件。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組分,其工作,你可以看到下面的圖片中:
而在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)}°</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>
);
}
如果將初始化邏輯轉換爲'componentDidMount'而不是'componentWillMount'會怎麼樣。由於該元素尚未安裝在DOM中,因此可能道具還沒有到達組件。一旦安裝,然後做這項工作。 https://facebook.github.io/react/docs/component-specs.html – lux
謝謝你的建議,不幸的是沒有什麼區別。 但是我剛剛意識到,如果我只是在渲染函數中返回道具,它會起作用,並且我會在頁面上看到渲染道具。 所以仍然不確定爲什麼'startApp()'函數無法訪問它們。 – chinds