簡體   English   中英

未捕獲的錯誤:對象作為 React 子項無效(發現:[object Promise])。 如果您打算渲染一組孩子,請使用數組 instea

[英]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.

相關問題 錯誤:對象作為 React 子對象無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組 錯誤:對象作為 React 子項無效(找到:[object Promise])。 如果您打算渲染一組孩子,請改用數組? 解決? 未捕獲的錯誤:對象作為 React 子對象無效(發現:object 和鍵 {todo})。 如果您打算渲染一組孩子,請使用數組 錯誤:對象作為 React 子對象無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。 (下一個) 對象作為 React 子項無效(找到:[object Promise])。 如果您打算渲染子集合,請改用數組。 錯誤 Uncaught Error:Objects are not valid as a React child (found: object with keys.If you meant to render a collection of children, use an array instead 未捕獲的錯誤:對象作為 React 子項無效(已找到:帶鍵的對象。如果您打算呈現子項集合,請改用數組 錯誤:對象作為 React 子項無效(找到:object,鍵為 {inputList})。 如果你打算渲染一個孩子的集合,使用一個數組 對象作為 React 子級無效(找到:object 和鍵 {children})。 如果您打算渲染一組孩子,請改用數組 對象作為 React 子級無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。(NEXT JS) 對象作為 React 子級無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。 ReactJS
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM