簡體   English   中英

為什么我不能將服務器的答案設置為狀態?

[英]Why can't I set server's answer to state?

我正在嘗試從 api.openweathermap.org 獲取 JSON 並將其設置為 state,但結果我得到了console.log

我應該怎么做將 JSON 的信息設置為 state.weather?

import React, { Component } from 'react';

class GetWeather extends Component {
    constructor(props) {
        super(props);
        this.state = {
            weather: {},
            temp: ''
        }
    };

        weather = async (e) => {
    e.preventDefault();
    try {
        let response = await fetch('http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b40640de9322c8facb1fcb9830e8b1f4');
        let data = await response.json();
        // if I will use response.text() here, than next console.log will show me the object literal that I got from server
        console.log('data: ' + data);
        await this.setState({weather: data});
        console.log('state ' + this)
    } catch (e) {
        console.log(e);
    }
}

    render() {
        return (
            <button onClick={this.weather} />
        )
    }
}

export default GetWeather;

React 狀態更新是異步的,並且發生在函數調用的末尾(即所有設置的狀態調用都被“整理”並一起處理,是協調的一部分),因此控制台在之后立即記錄狀態更新不起作用。

嘗試使用setState回調

this.setState({weather: data}, () => console.log('state', this.state));

狀態將在之后同步更新並調用回調,因此您將看到新的狀態值。 您也不需要等待它。

您不能await setState。 要在狀態改變后執行代碼, setState實際上有第二個參數,它是一個在狀態改變后執行的回調函數。 您的代碼應如下所示:

console.log(data);
this.setState({weather: data}, () => {console.log(this.state)});

在這里你可以看到另一個問題。 由於您將一個字符串 ('data:') 與一個對象連接起來,您的對象將被轉換為字符串並得到 [object Object]。 為避免這種情況,請僅打印對象或與字符串分開打印對象,如下所示: console.log('data:', data) 請注意,我在這里使用了逗號,而不是加號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM