![](/img/trans.png)
[英]Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead
[英]Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instea
編輯:(剛剛)為 App.js 插入更新的代碼
我正在嘗試創建一個帶有本機反應的小型天氣應用程序(不完整)。 它將顯示用戶當前位置今天的天氣,以及天氣預報(尚未實現)。 我正在嘗試獲取當天的溫度。 這是行不通的。
這是我的代碼,更多信息: App.js
import React from 'react'; import { Text, View } from 'react-native'; import WeatherComponent from './components/weather'; function fetchWeatherForToday(lat, lon) { let url = `http://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=imperial&appid=2b6b99284ca5506af3a162425a954d1e`; return fetch(url).then(response => response.json()) //convert response to json.then(responseJSON => { let temp = responseJSON.daily.temp; // temperature return Promise.resolve(temp) }) } export default class App extends React.Component { constructor() { super(); this.state = { temp: {} } } componentDidMount() { fetchWeatherForToday(35, -78).then((temp) => { this.setState({ temp: temp }) console.log(this.state.temp); }).catch((err) => console.error(err)) } render() { return ( <View> <WeatherComponent /> <Text>{/* Component that temporarily displays json, for testing purposes */}</Text> <Text>Weather App</Text> <Text>Weather for your location today:</Text> <Text>{JSON.stringify(this.state.temp)}</Text> <Text>{/*<Picker selectedValue={this.state.city} onValueChange={currentCity => this.setCity(currentCity)}> <Picker.Item label='Morrisville' value='Morrisville' /> <Picker.Item label='Cary' value='Cary' /> <Picker.Item label='Pune' value='Pune' /> </Picker>*/}</Text> </View> ); } }
組件/WeatherComponent.js
import React from 'react';
import { Text, View } from 'react-native';
import * as Location from 'expo-location';
export default class WeatherComponent extends React.Component {
constructor() {
super();
this.state = {
city: 'Morrisville',
location: null,
errorMsg: null
}
}
setLocation(location) {
this.setState({
location: location
})
}
setErrorMsg(message) {
this.setState({
errorMsg: message
})
}
setCity(city) {
this.setState({
city: city
})
}
async componentDidMount() {
try {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
this.setErrorMsg('You need to grant location access for the best services.');
return;
}
let location = await Location.getCurrentPositionAsync({});
this.setLocation(location);
} catch (error) {
console.log(error);
}
}
render() {
let text = 'Waiting..';
if (this.state.errorMsg) {
text = this.state.errorMsg;
} else if (this.state.location) {
text = JSON.stringify(this.state.location);
}
return (
<View>
<Text>{text}</Text>
</View>
);
}
}
我從 OpenWeatherMap API 獲得響應的片段:
async fetchWeatherForToday(lat, lon) { //lat=latitude,lon=longitude
let url = `http://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=imperial&appid=[REDACTED]`;
var result = await fetch(url)
.then(response => response.json()) //convert response to json
.then(responseJSON => {
let temp = responseJSON.daily.temp; // temperature
})
}
(PS 忽略 App.js 第 25-31 行的注釋代碼,測試目的)(由於字符限制,標題少了一個字母)
問題是您試圖在渲染 function 中調用異步提取。 最好在安裝時處理提取並將其加載到 state 值中,如下所示
import React from 'react'; import { Text, View } from 'react-native'; import WeatherComponent from './components/weather'; async function fetchWeatherForToday(lat, lon) { let url = `http://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=imperial&appid=[REDACTED]`; return fetch(url).then(response => response.json()) //convert response to json.then(responseJSON => { let temp = responseJSON.daily.temp; // temperature return Promise.resolve(temp) }) } export default class App extends React.Component { componentDidMount() { fetchWeatherForToday(35, -78).then((temp) => { this.setState({ temp }) }).catch((err) => console.error(err)) } render() { return ( <View> <WeatherComponent /> {/* Component that temporarily displays json, for testing purposes */} <Text>Weather App</Text> <Text>Weather for your location today:</Text> <Text>{this.state.temp || ""}</Text> </View> ); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.