【问题标题】:How can I utilize a variable in my setState function call?如何在我的 setState 函数调用中使用变量?
【发布时间】:2019-12-05 14:29:41
【问题描述】:

我正在尝试使用 setState 函数在此回调函数中将我的“绘图”状态设置为 json 对象“数据”。我知道“数据”对象已正确传递,因为我能够在 this.setState() 调用之前将其记录到控制台中,但是,当我尝试设置状态时,我收到“TypeError:不能读取未定义的属性‘setState’。” 代码如下:

constructor(props) {
    super(props);

    this.state = {
        plot: null,
    };

    this.getPlot = this.getPlot.bind(this);
    this.getPlot.fetchServiceData = fetchServiceData.bind(this);
}

getPlot() {
    fetchServiceData('/plot', function (data) {
        this.setState({plot: data}, function () {
            if(this.state.plot) {
                Bokeh.embed.embed_item(this.state.plot, 'AAPL_plot');
            }else{
                console.error('Unable to set plot state.')
            }
        });
    });
}

componentDidMount() {
    this.getPlot();
}

这是我的 fetchServiceData 函数,在另一个导入的文件中:

function fetchServiceData(apiPath, callback) {

let data = null;
fetch(BASE_SERVICE_URL + apiPath)
    .then(response => response.json())
    .then(function(data) {
        console.log(this)
        callback(data);
    })
    .catch(error => console.log(error));
}

export { fetchServiceData };

我是否需要以某种方式将“this”绑定到我的 fetchServiceData() 函数或该函数的回调?

【问题讨论】:

标签: reactjs components state


【解决方案1】:

错误很明确:您可以对未定义的值应用 setState 方法。
因此,您必须通过调用 .bind(this) 将您的上下文 this 绑定到您的方法。

【讨论】:

  • 我正在尝试实施您的解决方案,但无法使其正常工作。我只是试图通过说明来绑定它: this.getPlot.fetchServiceData = fetchServiceData.bind(this);在构造函数中,但上下文没有被继承。请问您的答案可以更具体一点吗?感谢您的帮助。
  • 你能用你所做的修改来编辑你的帖子吗?
  • 我已经添加了修改以及在 getPlot 中调用的函数。让我知道是否有任何其他有用的信息
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 2020-02-10
  • 1970-01-01
  • 2022-10-04
相关资源
最近更新 更多