React 组件生命周期 API 请求

React component lifecycle API request

我正在尝试向 FourSquare API 发出请求,它希望以 YYYYMMDD 的格式发送时间对象。我已经编写了一个生成时间对象的函数,但是我在我的 React 应用程序中使用它时遇到问题。

我在 Profile 组件中调用:

'use strict'

import React, { Component } from 'react'
import request from 'superagent'

import TimeService from './services/time'
import config from './config'

class Profile extends Component {

componentDidMount() {
  TimeService.getCurrentTime((err, currentDate) => {
    this.setState({
      time: currentDate
    })
  })
}

componentWillMount() {

  let currentTime = this.state.time
  let venue = '4dd64e9de4cd37c8938e7b83'
  //let venue = this.props.venueId
  let clientId = config.CLIENT_ID
  let clientSecret = config.CLIENT_SECRET

  request.get(`https://api.foursquare.com/v2/venues/${venue}/hours/?\&client_id=${clientId}&client_secret=${clientSecret}&v=${currentTime}`)
    .accept('json')
    .end((err, res) => {
      if(err) return
        let result = res.body
        console.log(res.body)
        console.log(result.response.hours.timeframes)
  })
}

当我在 Chrome 中加载应用程序时,出现以下错误消息:bundle.js:44492 Uncaught TypeError: Cannot read property 'time' of null

我的猜测是我需要重新排序组件安装方法中的功能,但我不确定如何。

在组件生命周期的特定点执行各种方法。

  • componentWillMount 在初始渲染发生之前执行一次。

  • componentDidMount在初始渲染后执行一次

您正在设置组件在 componentDidMount 中安装时的状态,但在 componentWillMount 之前使用它。

所以当你使用:

let currentTime = this.state.time

尚未定义 所以你得到一个 Cannot read property 'time' of null.

您应该在 componentWillMount 中设置您的状态,render() 将看到更新后的状态,并且尽管状态发生变化也只会执行一次。

之后,一旦安装了组件,你就可以执行你对 Foursquare API 的调用,你的 time 属性 状态将被定义,所以它不会不再触发错误。

您可以在 the documentation 中获得有关组件生命周期的更多信息。

本文档还指出发送 AJAX 请求的首选方法是 componentDidMount.

If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.