簡體   English   中英

如何用 class 組件重寫 useRef?

[英]How can I rewrite useRef with class component?

我需要以 JSON 格式獲取集成信息,並且需要幫助將 useRef(功能組件)轉換為 createRef(類組件)。 功能組件:

import { createTTNCClient } from '~/shared/clients/ttnc';

const DevicesTable: React.FC<Props> = (props) => {
        const TTNCClient = useRef(createTTNCClient());
          const fetchIntegrations = async (): Promise<Integration[]> => {
        try {
          const resp = await TTNCClient.current.getIntegrations();      
          return resp.data.content;
        } catch (err) {
          throw new Error(err);
        }
      };
    }

我試圖制作一個 Class 組件:

export class DevicesTable extends React.PureComponent<Props> {
  private TTNCClientRef: React.RefObject<any>;

  constructor(props) {
    super(props);
    this.TTNCClientRef = React.createRef();
  }
render() {
   const TTNCClient = this.TTNCClientRef.current.getIntegrations(); 
     
    const fetchIntegrations = async (): Promise<Integration[]> => {
      try {
        const resp = await TTNCClient;
        console.log(resp.data.content)
        return resp.data.content;
        } catch (err) {
        throw new Error(err);
        }
    };
 }
   return (
   <div></div>
 )
}

但它會引發有關 function getIntegrations() 的錯誤。 我猜是因為我沒有在 class 組件中添加“createTTNCClient”。 這是它與功能組件的外觀:

const TTNCClient = useRef(createTTNCClient());

但我不知道如何將“ createTTNCClient() ”添加到 class 組件中的“ createRef ”。

您的 class 組件代碼似乎沒有調用createTTNCClient構造函數。

您可能可以在 class 構造函數中執行此操作:

constructor(props) {
  super(props);
  this.TTNCClientRef = React.createRef();

  this.TTNCClientRef.current = createTTNCClient();
}

或者在componentDidMount生命周期方法中:

componentDidMount() {
  this.TTNCClientRef.current = createTTNCClient();
}

作為預防措施,在嘗試調用時應用一些空檢查:

const TTNCClient = this.TTNCClientRef.current?.getIntegrations();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM