我正在尝试从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成为类之外的一个函数,而不是一个方法,但我也遇到了错误。
有什么想法吗?
答案 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)
最后。