我目前正在尝试将class-based component重写为功能组件。在链接中,您可以找到一个特定的部分:
this.publisherId = uuid();
const { publisherId } = this;
this.errorHandler = once((err) => {
if (publisherId !== this.publisherId) {
// Either this publisher has been recreated or the
// component unmounted so don't invoke any callbacks
return;
}
if (typeof this.props.onError === 'function') {
this.props.onError(err);
}
});
const publisher = OT.initPublisher(container, properties, (err) => {
if (publisherId !== this.publisherId) {
// Either this publisher has been recreated or the
// component unmounted so don't invoke any callbacks
return;
}
函数createPublisher()
首先定义:this.publisherId = uuid();
,然后定义const { publisherId } = this;
。然后,它将在代码if (publisherId !== this.publisherId)
的不同部分中进行检查。我想知道,由于this
在那里不可用,您将如何为基于功能的组件编写检查?
答案 0 :(得分:0)
使用功能组件,您可以使用ref
保留渲染之间的变量值。
// Create an empty publisherId
const publisherIdRef = useRef();
// Assign it
publisherIdRef.current = uuid();
// Test it
if (publisherIdRef.current !== publisherId) ...