【发布时间】: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
//})
})
}
...
【问题讨论】:
-
查看Is it bad practice to have a constructor function return a Promise? 了解一般问题,尽管可能有特定于反应的解决方案。
标签: javascript reactjs constructor fetch-api