首页 > 解决方案 > 如何将设置状态抛出到全局变量

问题描述

我想将值扔给 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 }

标签: reactjs

解决方案


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

然后,如果你想改变它的值,你应该使用letand not 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

推荐阅读