繁体   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