如何将设置状态抛出全局变量

时间:2019-12-12 08:18:43

标签: reactjs

我想将值扔给const countBadge,但是我遇到未定义的错误。我如何将已获取的数据设置为全局变量?我需要导出新值

获取数据是正确的,因为另一方面,我在console.log上返回结果[0] .NumToApprove,其值为7。

const countBadge = this.state.numToApprove

class Notifications extends Component{
  constructor(props){
    super(props);
    this.state = {
      numToApprove: 0,
    }
  }
  fetchData = () =>{
    fetch(APILink + '/filing/get_badges', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: qs.stringify({
        'is_from_api': true
      })
      })
        .then(response => response.json())
        .then((result) => {
          this.setState({
            numToApprove: result[0].NumToApprove
          })
        }).catch(error => {
          alert('Transaction Error' + error)
        }
      );
  }
}

export { countBadge }

1 个答案:

答案 0 :(得分:1)

因此,首先,您在组件外部使用this,这将不会评估您的组件,因此countBadge将不会保留组件中的numToApprove

然后,如果要更改其值,则应使用let而不是const

所以这样的事情应该做:

let countBadge = 0

class Notifications extends Component{
  constructor(props){
    super(props);
    this.state = {
      numToApprove: 0,
    }
  }
  fetchData = () =>{
    fetch(APILink + '/filing/get_badges', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: qs.stringify({
        'is_from_api': true
      })
      })
        .then(response => response.json())
        .then((result) => {
          this.setState({
            numToApprove: result[0].NumToApprove
          })
          countBadge = /* ... the new value ... */
        }).catch(error => {
          alert('Transaction Error' + error)
        }
      );
  }
}

export { countBadge }

然后,如果您想在countBadge更改后立即更新另一个组件,则解决方案不是将其作为全局变量,因为全局变量在更改时不会触发UI更新。 相反,有两种解决方案:

  • countBadge置于Notifications和其他组件的最接近共同祖先的状态
  • 使用Redux
相关问题