'use strict';
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Image
} from 'react-native';
var Forecast=require('./Forecast');
const APIKEY = "API KEY";
var WeatherProject = React.createClass({
//if you want to have a default zip code, 넌 여기에 넣을 수 있다.
getInitialState(){
return {
zip:'', //우편 번호
forecast: null
};
},
_handleTextChange(event){
var zip= event.nativeEvent.text;
this.setState({zip:zip});
fetch('http://api.openweathermap.org/data/2.5/weather?zip='
+zip+'.KR&units=metric&APPID='+APIKEY)
.then((response) => response.json())
.then((responseJSON) => {
this.setState({
forecast: {
main: responseJSON.weather[0].main,
description: responseJSON.weather[0].description,
temp: responseJSON.main.temp
}
});
})
.catch((error) => {
console.warn(error);
});
},
render(){
var content = null;
if( this.state.forecast!==null){
content = <Forecast
main={this.state.forecast.main}
description={this.state.forecast.description}
temp={this.state.forecast.temp}/>;
}
return(
<View style={styles.container}>
<Image
source = {require('./img/flower.jpeg')}
resizeMode='cover'
style={styles.backdrop}>
<View style={styles.overlay}>
<View style={styles.row}>
<Text style={styles.mainText}>
Current weather for
</Text>
<View>
<TextInput
style={styles.zipCode}
returnKeyType='go'
onSubmitEditing={this._handleTextChange}/>
</View>
</View>
{content}
</View>
</Image>
</View>
);
}
});
var baseFontSize = 16;
var styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
paddingTop:5
},
backdrop: {
flex:1,
flexDirection:'column'
},
overlay:{
paddingTop:5,
backgroundColor:'#000000',
opacity:0.5,
flexDirection:'column',
alignItems:'center'
},
row:{
flex:1,
flexDirection:'row',
flexWrap:'nowrap',
alignItems:'flex-start',
padding:30
},
zipCode:{
width:70,
height:30,
marginLeft:5,
backgroundColor:'#FFFFFF',
fontSize:20,
padding:0,
color: '#000000'
},
mainText:{
flex:1,
fontSize:baseFontSize,
color:'#FFFFFF'
}
});
module.exports=WeatherProject;
在_handleTextChange(事件)函数
中.then((response) => response.json())
.then((responseJSON) => {
this.setState({
forecast: {
main: responseJSON.weather[0].main,
description: responseJSON.weather[0].description,
temp: responseJSON.main.temp
}
});
})
在这段代码中,TypeError:undefined不是一个对象(评估&#39; responseJSON.weather [0]&#39;)有一个错误..为什么这个错误发生了? 如何交换此代码才能正常执行?
答案 0 :(得分:1)
您的错误正在发生,因为您遗漏了一个有效的API密钥来查询OpenWeatherMap API。回复你所写的内容是:
{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}
通过此链接将解释设置帐户和创建API密钥以使用此服务的要求。
我使用OpenWeatherMap创建了一个帐户和API密钥,使用您的代码示例,弹出一个简单的无状态组件来转储传递给Forecast
组件的道具,以验证这是纠正错误所需的全部内容