【问题标题】:Get a constructor variable in promise在promise中获取构造函数变量
【发布时间】:2016-08-17 05:45:43
【问题描述】:

我无法在使用 javascript 的 fetch 调用中获取构造函数变量并做出反应。我想要 .then(function(json) 回调中 this.state.numXLabels 的值,但我得到 TypeError: Cannot read property 'state' of undefined(...)。这样做的正确方法是什么?这里是相关代码:

TypeError: 无法读取 undefined(...) 的属性“状态”

import React, { Component } from 'react'
class StockGraph extends Component {

constructor(props) {
    super(props);
    this.state = { numXLabels: 0 }
     var url = 'https://www.quandl.com/api/v3/datasets/WIKI/MSFT'+
           '.json?api_key=bCRpjzvgPNkxLzqAv2yY';
    fetch(url)
    .then(function(response) {
      return response.json()
    })
    .then(function(json) {
      console.log(this.state.numXLabels);
       //this.setState({
        // numXLabels: 30
       //})
    })
  }
...

【问题讨论】:

标签: javascript reactjs constructor fetch-api


【解决方案1】:

不要尝试在 React 组件的构造函数中使用状态或进行 ajax 调用。相反,将该调用放在立即触发的lifecycle methods 之一中,例如componentWillMount。此外,要在 ajax 回调中访问 this.state,您需要将 this 绑定到该函数。使用fat arrow function syntax 是最直接的方法。

class StockGraph extends Component {
    constructor(props) {
        super(props);
        this.state = { numXLabels: 0 }
    }

    componentWillMount() {
        var url = 'https://www.quandl.com/api/v3/datasets/WIKI/MSFT'+
           '.json?api_key=bCRpjzvgPNkxLzqAv2yY';
        fetch(url)
        .then((response) => {
           return response.json()
         })
        .then((json) => {
            console.log(this.state.numXLabels);
            //this.setState({
             // numXLabels: 30
           //})
        })
    }
    ...

【讨论】:

  • 谢谢!绑定是关键。迁移到 componentWillMount 也有利于结构清洁。胖箭头语法是一个很好的提示。也可以像这样实现:.then(function(json){ console.log(this.state.numXLabels); }.bind(this))
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2012-01-23
  • 1970-01-01
相关资源
最近更新 更多