了解基于类的组件以重写为功能组件

时间:2020-05-03 07:06:22

标签: reactjs

我目前正在尝试将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在那里不可用,您将如何为基于功能的组件编写检查?

1 个答案:

答案 0 :(得分:0)

使用功能组件,您可以使用ref保留渲染之间的变量值。

// Create an empty publisherId
const publisherIdRef = useRef();

// Assign it
publisherIdRef.current = uuid();

// Test it
if (publisherIdRef.current !== publisherId) ...