简体   繁体   English

为什么我不能将服务器的答案设置为状态?

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

I'm trying to get JSON from api.openweathermap.org and set it to state, but as result I get console.log我正在尝试从 api.openweathermap.org 获取 JSON 并将其设置为 state,但结果我得到了console.log

What should I do set JSON's info to state.weather?我应该怎么做将 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 state updates are asynchronous and occur at the end of the function call (ie all set state calls are "collated" and processed together, part of the reconciliation), so console logging the state update immediately after doesn't work. React 状态更新是异步的,并且发生在函数调用的末尾(即所有设置的状态调用都被“整理”并一起处理,是协调的一部分),因此控制台在之后立即记录状态更新不起作用。

Try to use the setState callback尝试使用setState回调

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

State will update and call the callback afterwards, synchronously, so you'll see the new state value.状态将在之后同步更新并调用回调,因此您将看到新的状态值。 You also do not need to await it.您也不需要等待它。

You cannot await setState.您不能await setState。 To execute code after your state has changed, setState actually has 2nd argument which is a callback function that is executed after the state has changed.要在状态改变后执行代码, setState实际上有第二个参数,它是一个在状态改变后执行的回调函数。 Your code should look something like this:您的代码应如下所示:

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

Here you can see another problem.在这里你可以看到另一个问题。 Since you are concatenating a string ('data:') with an object, your object is converted to the string and you get [object Object].由于您将一个字符串 ('data:') 与一个对象连接起来,您的对象将被转换为字符串并得到 [object Object]。 To avoid this, print either only the object or print an object separately from the string like this: console.log('data:', data) .为避免这种情况,请仅打印对象或与字符串分开打印对象,如下所示: console.log('data:', data) Note that I used a comma here, not a plus.请注意,我在这里使用了逗号,而不是加号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM