从componentDidMount调用函数(发出http请求)

时间:2019-08-06 14:49:48

标签: javascript reactjs http web axios

我正在用Reactjs编写一个应用程序。我想在打开组件/页面时进行api调用。

从componentDidMount()我调用另一个函数,该函数使用axios发出http请求。从该函数想将对象返回到componentDidMount(),在此尝试在控制台中打印它。

我尝试将http函数中的代码放入componentDidMount中,并且可以正常工作。

export class MyFunction extends Component {
  ...

  functionOne = () => {
    axios.get(API_FETCH_LINK)
      .then(response => response.data)
      .then((data) => {
        console.log("Data from db", data);              //PRINT ONE
        var date = new Date(Date.parse(data.timeStamp));
        console.log("Date from db", date);              //PRINT TWO
        return date;
        });
    };

  componentDidMount(){
  var date = this.functionOne();
  console.log("The date is ", date);                   //PRINT THREE
  }

 ...
}

PRINT ONE和PRINT TWO 2的输出有意义,但PRINT THREE 3显示“未定义”。有人知道为什么吗?

1 个答案:

答案 0 :(得分:-1)

export class MyFunction extends Component {
    functionOne = () => {
        return axios.get(API_FETCH_LINK)
            .then(response => response.data)
            .then(data => {
                console.log("Data from db", data); //PRINT ONE
                var date = new Date(Date.parse(data.timeStamp));
                console.log("Date from db", date); //PRINT TWO
                return date;
            });
    };

    componentDidMount() {
        this.functionOne().then(date => console.log("The date is ", date));
    }
}