Javascript React将状态设置为API调用的结果

Javascript React将状态设置为API调用的结果,javascript,reactjs,Javascript,Reactjs,我正在调用一个返回datetime的getTime函数,但是由于某种原因,我指定的状态没有被更新,我是否误解了它的工作原理?我需要等待结果吗 import * as React from 'react'; import {getTime} from '../utilities/time-helper' export default class Landing extends React.Component { constructor(props) { super(pro

我正在调用一个返回datetime的getTime函数,但是由于某种原因,我指定的状态没有被更新,我是否误解了它的工作原理?我需要等待结果吗

import * as React from 'react';
import {getTime} from '../utilities/time-helper'

export default class Landing extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            london: null,
            paris: null
        };
      }

    componentDidMount() {
        this.setState({ london: getTime("Europe/London") });
        this.setState({ paris: getTime("Europe/Paris") });
    }

    render() {
        return (
                <div>
                    <h1>London Time: {this.state.london}</h1>
                    <h1>Paris Time: {this.state.paris}</h1>
                </div>
        );
    }
    
}

// time-helper.js
export function getTime(timezone) {
    let url = 'http://worldtimeapi.org/api/timezone/' + timezone;

    fetch(url)
    .then(res => res.json())
    .then((out) => {
        return out.datetime
    })
    .catch(err => { throw err });
}
import*as React from'React';
从“../utilities/time helper”导入{getTime}
导出默认类登录扩展React.Component{
建造师(道具){
超级(道具);
此.state={
伦敦:空,
巴黎:空
};
}
componentDidMount(){
this.setState({london:getTime(“欧洲/伦敦”)});
this.setState({paris:getTime(“欧洲/巴黎”)});
}
render(){
返回(
伦敦时间:{this.state.London}
巴黎时间:{this.state.Paris}
);
}
}
//time-helper.js
导出函数getTime(时区){
让url为空http://worldtimeapi.org/api/timezone/“+时区;
获取(url)
.then(res=>res.json())
.然后((输出)=>{
返回out.datetime
})
.catch(err=>{throw err});
}

是的,确切地说,这是一个获取,因此您必须等待结果,然后才设置状态,这样您就可以执行smth,如:

componentDidMount() {
  getTime('Europe/London')
    .then((response) => this.setState({ london: response });
}

我尝试了类似的方法,但得到了未捕获的TypeError:无法读取未定义的属性'then'。是因为getTime承诺没有得到完全解决吗?检查您的fn返回了什么(
out
,在您的情况下),我认为这只是返回的问题,但您有。