2

我需要以 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>
 )
}

但它会引发有关函数 getIntegrations() 的错误。我猜是因为我没有在类组件中添加“createTTNCClient”。这是功能组件的外观:

const TTNCClient = useRef(createTTNCClient());

但我不知道如何在类组件中添加“ createTTNCClient()”到“ ”。createRef

4

1 回答 1

3

您的类组件代码似乎没有调用createTTNCClient构造函数。

您可能可以在类构造函数中执行此操作:

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

  this.TTNCClientRef.current = createTTNCClient();
}

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

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

作为预防措施,在尝试调用时应用一些空检查:

const TTNCClient = this.TTNCClientRef.current?.getIntegrations();
于 2022-03-01T09:15:52.323 回答