电子:将Reaction组件状态从main.js更改

2022-02-23 00:00:00 reactjs node.js electron javascript

我有一个电子应用程序,其中包括以下文件:

  • index.js
  • browserwindow.html
  • browserwindow.js(从browserwindow.jsx编译而来)

index.js是电子应用程序启动时运行的主电子/节点进程。browserwindow.htmlguiWindow中呈现,browserwindow.js管理此窗口。(请参见下面的文件。)

我想要的是从主电子进程向browserwindow.js发送一条IPC消息,然后更新Reaction组件状态。但是,当我使用下面文件中的代码并运行电子应用程序时,状态不会更改。

index.js

const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;
const app = electron.app;
const url = require('url');
const ipc = electron.ipcMain;


app.on('ready', function(){

  // Make window
  var guiWindow;

  // Set size and do not immediately show
  guiWindow = new BrowserWindow({
    width: 800,
    height: 780,
    show: false
  });

  // Load browserwindow.html in the guiWindow
  guiWindow.loadURL('file://' + __dirname + '/browserwindow.html');

  // Show the window when the .html file is loaded
  guiWindow.once('ready-to-show', function(){
    guiWindow.show();
  });

  // Send an ipc after 3 seconds
  setInterval(function(){
    guiWindow.webContents.send('message', {msg: 'Hello World!'});
  }, 3000);

});

browserwindow.html

<!DOCTYPE html>
<html>
  <head>
    <title>Page</title>
  </head>
  <body>
    <!-- The div that React uses: -->
    <div id="mainInterface"></div>
    <script src="react-0.14.3.js"></script>
    <script src="react-dom-0.14.3.js"></script>
    <script src="browserwindow.js"></script>
  </body>
</html>

编译为browserwindow.js的JSX

var electron = require('electron');
var shell = electron.shell;
var ipc = electron.ipcRenderer;

class MainInterface extends React.Component {

  constructor(props, contect){
    super(props);
    this.state = {
      testValue: 'Initial state'
    };
  };

  componentDidMount(){ // When the document is rendered

    ipc.on('message', function(event, data){ // When the message is received...
      console.log('Message received');
      this.setState({testValue: 'It worked!'}); // ... change the state of this React component
    });

  }

  render(){
    return (
      <h1>{ this.state.testValue }</h1>
    );
  }

}

ReactDOM.render(
  <MainInterface />,
  document.getElementById('mainInterface')
);

在Javascript控制台中,我收到以下错误:

Uncaught TypeError: this.setState is not a function
    at EventEmitter.<anonymous> (file:///C:/Users/<file path to the project on my computer>/testproject/browserwindow.js:20:12)
    at emitTwo (events.js:106:13)
    at EventEmitter.emit (events.js:194:7)

我可以做些什么来解决此问题?

(对于一些背景,我正在制作一个Electron应用程序,它应该通过MQTT接收消息,并根据收到的消息更新屏幕上的元素。)


解决方案

您的this指向与组件实际不同的上下文。您需要将代码更改为

componentDidMount() {
    // When the document is rendered.
    const self = this;
    ipc.on('message', function (event, data) {
        // When the message is received...
        console.log('Message received');
        // ... change the state of this React component.
        self.setState({testValue: 'It worked!'});
    });
}

或者您可以将function()回调替换为() => {},因为第一个选项更改了执行的上下文。

相关文章