我有一个使用本机react和Open Weather API的天气应用程序。从weatherConditions.js文件调用图标时出现问题。未定义不是对象weatherConditions [weather] .icon
这是Home.js
import { API_KEY } from '../../utils/WeatherAPIKey';
import Weather from './../../components/Weather';
class Home extends React.Component {
state = {
isLoading: false,
temperature: 0,
weatherCondition: null,
error: null
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
position => {
this.fetchWeather(position.coords.latitude, position.coords.longitude);
},
error => {
this.setState({
error: 'Error Gettig Weather Condtions'
});
}
);
}
fetchWeahter(lat, lon) {
fetch(
`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&APPID=${API_KEY}&units=metric`
)
.then(res => res.json())
.then(json => {
// console.log(json);
this.setState({
temperature: json.main.temp,
weatherCondition: json.weather[0].main,
isLoading: false
});
});
}
render() {
const { isLoading, weatherCondition, temperature } = this.state;
return (
<View style={styles.container}>
{isLoading ? (
<View style={styles.loadingContainer}>
<Text style={styles.loadingText}>Fetching The Weather</Text>
</View>
) : (
<Weather weather={weatherCondition} temperature={temperature} />
)}
</View>
);
}
}
export default Home;
这是Weather.js
import ...
import { MaterialCommunityIcons } from '@expo/vector-icons';
import PropTypes from 'prop-types';
import { weatherConditions } from '../utils/WeatherConditions';
const Weather = ({ weather, temperature }) => {
return (
<View style={styles.headerContainer}>
<MaterialCommunityIcons
size={72}
name={weatherConditions[weather].icon}
color={'#000'}
/>
<Text style={styles.tempText}>{temperature}˚</Text>
</View>
);
};
Weather.propTypes = {
temperature: PropTypes.number.isRequired,
weather: PropTypes.string
};
const styles = StyleSheet.create({...})
这是WeatherConditions.js
export const weatherConditions = {
Rain: { icon: 'weather-rainy' },
Clear: { icon: 'weather-sunny' },
Thunderstorm: { icon: 'weather-lightning' },
Clouds: { icon: 'weather-cloudy' },
Snow: { icon: 'weather-snowy' },
Drizzle: { icon: 'weather-hail' },
Haze: { icon: 'weather-hail' },
Mist: { icon: 'weather-fog' }
};
在Weather.js中调用{weatherConditions [weather] .icon}
时出现错误屏幕
答案 0 :(得分:0)
尝试写作
if (weatherCondition !== undefined) {
<Weather weather={weatherCondition} temperature={temperature} />
}