gpt4 book ai didi

javascript - React 中的函数未定义错误

转载 作者:行者123 更新时间:2023-11-30 14:54:16 25 4
gpt4 key购买 nike

我正在尝试从 componentDidMount 调用一个设置状态的函数,但不断遇到错误

未捕获的 ReferenceError:setPanelState 未定义

下面是代码...

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 成为类之外的函数而不是方法,但我也在那里遇到错误。

有什么想法吗?

最佳答案

由于您使用的是 ES6 类,因此我假设您已全部设置好。

使用自动绑定(bind) this 的箭头函数

要了解有关箭头函数的更多信息,请参阅 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);
})
}

关于javascript - React 中的函数未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com