在回调函数中出现状态错误?

In call back Function getting state error?

最初我有状态变量url: ''

let data = this.state.content;
    ContractAction._generatePDF(data, function(data){
        let filename = data.filename;
        let accesstoken = localStorage.getItem('accessToken');
        this.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });

    });

在 API 调用之后,在回调中我试图将 url 状态设置为给定的 url 但它没有更新

我遇到状态错误Cannot read property 'state' of undefined

我希望 url 状态更改为 http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken

因为this有范围问题。

之所以得到 setState of undefined,是因为 this 在回调中未定义。因为它当前指向回调的实例而不是整个 class 本身。你最好使用 Arrow functions 来处理这些问题 -

  • You don't need to keep typing function
  • It lexically captures the the meaning of this
  • It lexically captures the meaning of arguments

这样做

ContractAction._generatePDF(data, (data) => {
        let filename = data.filename;
        let accesstoken = localStorage.getItem('accessToken');
        this.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });
    });

或者定义为作用域变量

let data = this.state.content;
let scope = this;

并使用

scope.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });