Javascript 在电子渲染中调用react函数
我试图从react with ipc调用以下函数Javascript 在电子渲染中调用react函数,javascript,reactjs,electron,Javascript,Reactjs,Electron,我试图从react with ipc调用以下函数 componentDidMount() { ipcRenderer.on('log-out', function () { localStorage.setItem('user', 'null'); this.forceUpdate(); }); } 但每次我调用它,我都会得到以下错误 Uncaught TypeError: this.forceUpdate is not a function
componentDidMount() {
ipcRenderer.on('log-out', function () {
localStorage.setItem('user', 'null');
this.forceUpdate();
});
}
但每次我调用它,我都会得到以下错误
Uncaught TypeError: this.forceUpdate is not a function
at EventEmitter.<anonymous> (App.js:30)
at emitOne (events.js:96)
at EventEmitter.emit (events.js:191)
未捕获类型错误:this.forceUpdate不是函数
在黄昏时分。(App.js:30)
在emitOne(events.js:96)
在EventEmitter.emit上(events.js:191)
我做错了什么,或者应该怎么做
多谢各位 这是胖箭最常见的问题 在这里,您可以阅读有关fat arrow()的更多信息 我们可以通过两种方式解决此问题:
第一: 替换此项: 与:
第二:
本部分:
componentDidMount() {
ipcRenderer.on('log-out', function() {
localStorage.setItem('user', 'null');
this.forceUpdate();
});
}
this.forceUpdate()中的this
不是您要查找的此
。要解决此问题,您需要将此绑定到相应的上下文(您的组件),如下所示:
或者使用this
到self
创建闭包,如:
componentDidMount() {
self = this;
ipcRenderer.on('log-out', function() {
localStorage.setItem('user', 'null');
self.forceUpdate();
});
}
谢谢,我试过了,但是现在我得到了这个错误和另一个错误。在(…)上。bind不是一个函数
ipcRenderer.on('log-out', function () {
localStorage.setItem('user', 'null');
this.forceUpdate();
}).bind(this);
componentDidMount() {
ipcRenderer.on('log-out', function() {
localStorage.setItem('user', 'null');
this.forceUpdate();
});
}
componentDidMount() {
ipcRenderer.on('log-out', function() {
localStorage.setItem('user', 'null');
this.forceUpdate();
}.bind(this));
}
componentDidMount() {
self = this;
ipcRenderer.on('log-out', function() {
localStorage.setItem('user', 'null');
self.forceUpdate();
});
}