React

时间:2017-11-30 11:58:32

标签: javascript reactjs

我正在尝试从componentDidMount调用一个函数来设置State但是一直遇到错误

Uncaught ReferenceError: setPanelState is not defined

以下是代码......

export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
     PATIENT: [],
     COMPPROPS: [],
    };

    this.setPanelState = this.setPanelState.bind(this);
  }

    setPanelState(activity) {
          this.setState({COMPPROPS: [{compName:'Overview', compState:'Edit'}]});
    }

    componentDidMount() {   
       //handles chat commands and if the command is update patient the Overview panel should change to editable
       this.directLine.activity$
        .filter(function (activity) {
          return activity.type === 'event' && activity.value === 'Update Patient';
       })
       .subscribe(function (activity) {
         setPanelState(activity);   
       })
  }

我试过让setPanelState成为类之外的一个函数,而不是一个方法,但我也遇到了错误。

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

由于您正在使用ES6课程,我认为您已经完成了所有设置。

使用自动绑定的箭头功能

要了解有关箭头功能的更多信息,请参阅this

.subscribe((activity) => {
    this.setPanelState(activity);   
})

您的组件如下所示:

 export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
     PATIENT: [],
     COMPPROPS: [],
    };

    this.setPanelState = this.setPanelState.bind(this);
  }

    setPanelState(activity) {
          this.setState({COMPPROPS: [{compName:'Overview', compState:'Edit'}]});
    }

    componentDidMount() {   
       //handles chat commands and if the command is update patient the Overview panel should change to editable
       this.directLine.activity$
        .filter((activity) => {
          return activity.type === 'event' && activity.value === 'Update Patient';
       })
       .subscribe((activity) => {
         this.setPanelState(activity);   
       })
  }

答案 1 :(得分:0)

使用this.setPanelState(activity)并记住要维护上下文。因为你是非ES6 arraow函数。保存var = this的外部上下文并访问

中的变量

答案 2 :(得分:0)

使用componentDidMount

setPanelState方法调用this.setPanelState

您还可以使用更好的格式:

.subscribe(this.setPanelState)

如果您将setPanelState放在课堂外并打电话给它,它将无效, 除非在另一个可以使用setState的类中定义。

答案 3 :(得分:0)

更改为

 this.setPanelState(activity)

最后。