在使用回调的自定义事件处理设置中,回调的调用上下文显示回调参数的有效值,但在进入函数后参数值未定义。
以防万一,这是在使用 React 的 Electron 渲染器进程内部。
在普通的 JavaScript 对象中,调试器显示回调报告行中所有内容的预期上下文值 SerialPortEvent.Opened
.
// file: serialPort.js (no imports)
class SerialPortEvent {
Discovered = 0
Opened = 1
Closed = 2
DataReceived = 3
Error = 4
}
class SerialPortSpec {
...
addEventListener(listener) {
this.listeners.push(listener)
}
open(baudRate) {
const baudRateInt = parseInt(baudRate, 10)
window.serialport.open(this.portInfo.path, baudRateInt)
.then(binding => {
this.baudRate = baudRateInt
this.binding = binding
// Here, the debugger shows all locals are as expected
this.listeners.forEach(listener => listener(SerialPortEvent.Opened))
}).catch(reason => {
this.listeners.forEach(listener => listener(SerialPortEvent.Error, reason))
})
}
...
}
...
module.exports = { SerialPortEventHub, SerialPortSpec, SerialPortEvent }
然而,一个“step into”之后,在回调函数“portEventHandler”的开头,参数值为undefined
。我很想知道为什么!谢谢。
// file SerialPortUI.jsx
import React from 'react'
import { SerialPortEventHub, SerialPortEvent, SerialPortSpec } from './serialPort'
import './serialportui.css'
class SerialPortPanel extends React.Component {
...
portEventHandler(eventType, ...data) {
// Here, eventType is undefined. This file does import SerialPortEvent.
switch (eventType) {
...
}
}
...
}
class SerialPortEvent { Discovered = 0 Opened = 1 Closed = 2 DataReceived = 3 Error = 4 }
这不是正确的枚举声明。类字段将在实例上创建,您在代码中访问的静态类属性 SerialPortEvent.Opened
确实是 undefined
。这就是被调用函数接收到的值。
相反,您需要使用具有以下属性的对象:
const SerialPortEvent = {
Discovered: 0,
Opened: 1,
Closed: 2,
DataReceived: 3,
Error: 4,
};
永远不要使用 class
语法,如果你从来没有实例化它(使用 new
)!