Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 关于React中setState内部函数的问题_Javascript_Reactjs_State - Fatal编程技术网

Javascript 关于React中setState内部函数的问题

Javascript 关于React中setState内部函数的问题,javascript,reactjs,state,Javascript,Reactjs,State,我遇到了一个问题,我无法在React中的某个函数中执行setState函数。我浏览了一下解决方案,似乎我需要使用arrow函数或bind函数,但我仍然不明白它是如何工作的。以下是我的代码: class App extends Component { constructor(props) { super(props); this.state = { teamsId: "" }; } componentDidMount() { var x = "";

我遇到了一个问题,我无法在React中的某个函数中执行setState函数。我浏览了一下解决方案,似乎我需要使用arrow函数或bind函数,但我仍然不明白它是如何工作的。以下是我的代码:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { teamsId: "" };
  }

  componentDidMount() {
      var x = "";

      /*
          some initialization here, but not really relevant to my question
      */

      //Test context
      microsoftTeams.getContext(function(context) 
      {
        //in this part, x is filled with the Id, but how to pass the value to state? 
        x = context.teamId;
        console.log(x);
      })

      //in this part, x is empty again
      console.log(x);
      this.setState({ teamsId: x }); 
  }
}

如何将context.teamId传递到我的状态?

microsoftTeams.getContext()的参数是一个函数,也称为回调。因此,
getContext
部分执行一些异步操作,然后在完成时调用回调。Async stuff延迟到当前函数完成,因此要访问它,可以将
setState
调用放在回调函数中。问题是,似乎无法识别setState函数。它显示“TypeError:无法读取null的属性'setState',您需要将该回调转换为箭头函数,即
microsoftTeams.getContext((context)=>{//setState here})
。这样,
this
的正确值就会被传递到回调函数中,
microsoftTeams.getContext()
的参数是一个函数,也称为回调函数。因此,
getContext
部分执行一些异步操作,然后在完成时调用回调。Async stuff延迟到当前函数完成,因此要访问它,可以将
setState
调用放在回调函数中。问题是,似乎无法识别setState函数。它显示“TypeError:无法读取null的属性'setState',您需要将该回调转换为箭头函数,即
microsoftTeams.getContext((context)=>{//setState here})
。这样,
this
的正确值就会被传递到回调中