为什么我不能将服务器的回答设置为状态?
Why can't I set server's answer to state?
我试图从 api.openweathermap.org 获取 JSON 并将其设置为状态,但结果我得到 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 状态更新是异步的,发生在函数调用的末尾(即所有设置状态调用都是 "collated" 并一起处理,是协调的一部分),因此控制台不会在之后立即记录状态更新没用。
尝试使用setState
回调
this.setState({weather: data}, () => console.log('state', this.state));
State 之后会同步更新并调用回调,因此您会看到新的状态值。您也无需等待。
您不能await
setState。要在状态更改后执行代码,setState
实际上有第二个参数,它是在状态更改后执行的回调函数。您的代码应如下所示:
console.log(data);
this.setState({weather: data}, () => {console.log(this.state)});
在这里你可以看到另一个问题。由于您将一个字符串 ('data:') 与一个对象连接起来,因此您的对象将转换为该字符串,并且您会得到 [object Object]。为避免这种情况,请仅打印对象或像这样与字符串分开打印对象:console.log('data:', data)
。请注意,我在这里使用了逗号,而不是加号。
我试图从 api.openweathermap.org 获取 JSON 并将其设置为状态,但结果我得到 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 状态更新是异步的,发生在函数调用的末尾(即所有设置状态调用都是 "collated" 并一起处理,是协调的一部分),因此控制台不会在之后立即记录状态更新没用。
尝试使用setState
回调
this.setState({weather: data}, () => console.log('state', this.state));
State 之后会同步更新并调用回调,因此您会看到新的状态值。您也无需等待。
您不能await
setState。要在状态更改后执行代码,setState
实际上有第二个参数,它是在状态更改后执行的回调函数。您的代码应如下所示:
console.log(data);
this.setState({weather: data}, () => {console.log(this.state)});
在这里你可以看到另一个问题。由于您将一个字符串 ('data:') 与一个对象连接起来,因此您的对象将转换为该字符串,并且您会得到 [object Object]。为避免这种情况,请仅打印对象或像这样与字符串分开打印对象:console.log('data:', data)
。请注意,我在这里使用了逗号,而不是加号。