每当安装应用程序组件时,我都会尝试进行更新以更新窗口
状态。使用下面的代码,我收到 响应 tabs.query 的错误:TypeError: this.addTabs is not a function
。
我不明白为什么 this.addTabs 不被视为函数,因为该函数位于对 this.addTabs(tabs) 的引用之上,并且我认为它已正确绑定(bind)。
class App extends Component {
constructor(props){
super(props);
this.state = {
window: []
};
this.addTabs = this.addTabs.bind(this);
}
addTabs(tabs){
this.setState({window:this.state.window.concat(tabs)});
};
componentDidMount(){
chrome.tabs.query({active:true},function(tabs){
this.addTabs(tabs);
});
我不想使用箭头功能。我查看了类似的问题,答案是在构造函数中绑定(bind)函数,我相信我做到了。任何帮助或指示将不胜感激!
最佳答案
您的问题在此 block 中:
componentDidMount(){
chrome.tabs.query({active:true},function(tabs){
this.addTabs(tabs);
});
}
在回调中,上下文不同,因此 this
引用另一个上下文。
您有多种方法可以修复它。
1) 在回调之外将引用分配给 this 并使用该引用:
componentDidMount(){
const that = this;
chrome.tabs.query({active:true},function(tabs){
that.addTabs(tabs);
});
}
2)将当前的this绑定(bind)到回调:
componentDidMount(){
chrome.tabs.query({active:true},(function(tabs){
this.addTabs(tabs);
}).bind(this));
}
3)使用箭头函数:
componentDidMount(){
chrome.tabs.query({active:true}, (tabs) => {
this.addTabs(tabs);
});
}
关于javascript - JS React : error of this. x 不是函数,即使绑定(bind)了 this.x 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905045/