首页 > 解决方案 > 无法在 request.post 方法中设置状态

问题描述

您好,我正在尝试将我从后端获得的响应设置为状态。但我总是得到这个错误。

TypeError:this.setState 不是函数

有人可以告诉我如何设置对状态的响应吗?

recalcRequest(data){
   let meth = data
   let brandCode = meth.brandCode
   let paymentAmount = this.props.location.query.anfrage.umsatz+"00"
   let merchantReference = this.props.location.query.cardid
   let jsonData = {
            brandCode : brandCode,
            paymentAmount : paymentAmount,
            merchantReference:merchantReference
                    };

  request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url:     'http://localhost:8888/Backend/recalcSig.php',
    body:    "data=" + JSON.stringify(jsonData)
  }, function(err, response, body){
    if (err) throw err;
      body = JSON.parse(body)
      this.setState({
        merchantSig: body.merchantSig,
        sessionValidity: body.request.sessionValidity,
        requestPaymentMethods: false,
        showCardDetails:true
      })
    console.log('response: ', response);
  })

 }

标签: javascriptreactjsecmascript-6requestresponse

解决方案


使用箭头函数进行回调。

request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url:     'http://localhost:8888/Backend/recalcSig.php',
    body:    "data=" + JSON.stringify(jsonData)
  },(err, response, body) => {
    if (err) throw err;
      body = JSON.parse(body)
      this.setState({
        merchantSig: body.merchantSig,
        sessionValidity: body.request.sessionValidity,
        requestPaymentMethods: false,
        showCardDetails:true
      })
    console.log('response: ', response);
  })

推荐阅读