【发布时间】:2017-01-21 11:55:50
【问题描述】:
构建一个小的 react 应用程序,将地理位置(由浏览器确定为 props 的子组件)传递。
第一个组件: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>
);
}
}
该组件确定位置,将纬度和经度保存到 state 并通过 props 将此信息传递给 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>
)
}
}
真的不确定问题是什么,因为 react 开发工具显示天气组件确实在传递给该组件的道具中设置了位置。
编辑**已解决:
所以问题是状态是异步设置的,并且我的天气组件是在状态更新之前呈现的。
在渲染方法期间对状态值的简单检查解决了这个问题。
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 中,因此 props 可能尚未到达组件。一旦安装,然后做工作。 facebook.github.io/react/docs/component-specs.html -
感谢您的建议,遗憾的是这并没有什么不同。但是我刚刚意识到,如果我只是在渲染函数中返回道具,它就可以工作,并且我会在页面上看到渲染的道具。所以仍然不确定为什么
startApp()函数无法访问它们。
标签: reactjs components state