React Native新手:如何通过Darksky API展示未来24小时与7天天气数据
嘿,作为刚入坑React Native的新手,我太懂你想把天气数据快速展示出来的迫切感了!下面我一步步给你拆解怎么实现未来24小时和7天的天气展示,都是实操性的内容:
第一步:获取并解析Dark Sky API的数据
首先你得先调用API拿到数据,不管用fetch还是axios都可以,我这里用fetch举例子:
import { useState, useEffect } from 'react'; const WeatherScreen = () => { const [hourlyData, setHourlyData] = useState([]); const [dailyData, setDailyData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchWeatherData = async () => { try { // 注意:把YOUR_API_KEY换成你自己的Dark Sky密钥,坐标换成目标位置 const response = await fetch(`https://api.darksky.net/forecast/YOUR_API_KEY/37.8267,-122.4233?units=si`); const data = await response.json(); // Dark Sky返回的hourly.data就是未来24小时的逐小时数据 setHourlyData(data.hourly.data); // daily.data则是未来7天的逐日数据 setDailyData(data.daily.data); setLoading(false); } catch (error) { console.error('获取天气数据失败:', error); setLoading(false); } }; fetchWeatherData(); }, []); // 后面的UI渲染写在这里 }; export default WeatherScreen;
这里要注意:API返回的时间戳是秒级的,后面转成日期的时候要乘以1000转换成毫秒级。
第二步:展示未来24小时天气(横向滚动)
24小时数据适合用横向滚动的列表,React Native的ScrollView加horizontal属性就能实现。我们可以给每个小时做个小卡片,展示时间、温度和天气图标:
import { View, ScrollView, Text, StyleSheet, Image } from 'react-native'; // 先写个处理时间的小函数,把时间戳转成小时(比如14:00) const formatHour = (timestamp) => { const date = new Date(timestamp * 1000); return `${date.getHours()}:00`; }; // 渲染24小时天气的部分 if (loading) { return <Text style={styles.loadingText}>加载中...</Text>; } return ( <View style={styles.container}> <Text style={styles.sectionTitle}>未来24小时天气</Text> <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.hourlyScroll}> {hourlyData.map((hour, index) => ( <View key={index} style={styles.hourCard}> <Text style={styles.hourText}>{formatHour(hour.time)}</Text> {/* 这里可以用天气图标,比如react-native-vector-icons或者自定义图片,根据hour.icon字段匹配 */} <Text style={styles.tempText}>{Math.round(hour.temperature)}°</Text> <Text style={styles.summaryText}>{hour.summary}</Text> </View> ))} </ScrollView> {/* 7天天气的部分放在下面 */} </View> ); // 样式部分 const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, sectionTitle: { fontSize: 20, fontWeight: 'bold', marginBottom: 12, }, hourlyScroll: { marginBottom: 24, }, hourCard: { alignItems: 'center', marginRight: 16, padding: 12, backgroundColor: '#f0f0f0', borderRadius: 8, width: 80, }, hourText: { fontSize: 14, marginBottom: 8, }, tempText: { fontSize: 18, fontWeight: 'bold', marginBottom: 4, }, summaryText: { fontSize: 12, textAlign: 'center', }, });
第三步:展示未来7天天气
7天数据适合用纵向列表,用FlatList或者直接map遍历都可以,这里用map更直观(数据量小的时候完全够用):
// 先写个处理日期的函数,转成星期几或者完整日期 const formatDate = (timestamp) => { const date = new Date(timestamp * 1000); const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; return weekdays[date.getDay()]; }; // 在刚才的return里添加7天天气的部分 <Text style={styles.sectionTitle}>未来7天天气</Text> <View style={styles.dailyContainer}> {dailyData.map((day, index) => ( <View key={index} style={styles.dayCard}> <Text style={styles.dayText}>{formatDate(day.time)}</Text> <View style={styles.tempContainer}> <Text style={styles.highTempText}>{Math.round(day.temperatureHigh)}°</Text> <Text style={styles.lowTempText}>{Math.round(day.temperatureLow)}°</Text> </View> <Text style={styles.daySummaryText}>{day.summary}</Text> </View> ))} </View> // 补充样式 const styles = StyleSheet.create({ // ...之前的样式 dailyContainer: { gap: 12, }, dayCard: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16, backgroundColor: '#f0f0f0', borderRadius: 8, }, dayText: { fontSize: 16, fontWeight: '500', width: 60, }, tempContainer: { flexDirection: 'row', gap: 8, }, highTempText: { fontSize: 16, fontWeight: 'bold', }, lowTempText: { fontSize: 16, color: '#666', }, daySummaryText: { fontSize: 14, flex: 1, textAlign: 'right', marginLeft: 8, }, });
一些实用小贴士
- 天气图标:可以用
react-native-vector-icons库,根据Dark Sky返回的icon字段(比如"clear-day"、"rain")匹配对应的图标,或者自己找一套天气图标资源。 - 错误处理:可以加个错误状态,当API请求失败时显示错误提示,比如“加载天气数据失败,请稍后重试”。
- 环境变量:不要把API密钥硬编码在代码里,用
react-native-dotenv之类的工具把密钥存在环境变量里,更安全。 - 单位适配:API请求里的
units=si是公制单位,如果你要显示英制可以改成units=us。
如果还有细节问题,比如样式调整、图标适配或者数据缓存,随时问!
内容的提问来源于stack exchange,提问作者Hoàng Văn Việt
相关产品推荐
相关产品推荐

