构建一个小型反应应用程序,通过地理位置(由浏览器确定为子组件作为道具)。
第一个组成部分: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>
);
}
}
此组件确定位置,将纬度和经度保存到状态,并通过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>
)
}
}
真的不确定问题是什么,因为反应开发工具显示天气组件确实在道具中设置了传递到该组件的位置。
编辑**已解决:
所以问题是状态是异步设置的,我的天气组件是在状态更新之前呈现的。
在渲染方法期间对状态内的值进行简单检查即可解决问题。
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>
);
}
答案 0 :(得分:10)
我认为问题如下。 SetState异步发生。因此,在纬度和经度道具有数据之前,渲染功能会被触发。如果在渲染Weather组件之前有一些if检查,则可能不会出现此问题。这是我的意思的一个例子。
render() {
let myComponent;
if(check if props has val) {
myComponent = <MyComponent />
} else {
myComponent = null
}
return (
<div>
{myComponent}
</div>
)
}
答案 1 :(得分:2)
您必须将startApp()
和getWeather()
绑定到组件,否则this
将undefined
。
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);
}
...
}
答案 2 :(得分:0)
您需要保持渲染尽可能干净。避免在render中进行else if操作,而要在else中直接使用三元运算符或&&运算符进行检查。进行如下所示的条件检查,然后才调用MyComponent如下所示
render() {
return (
<div>
{this.state.latitude != '' && this.state.longitude != '' ? <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } />: null}
{this.state.latitude != '' && this.state.longitude != '' && <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } />}
</div>
)
}