如何用类组件重写 useRef ?
我需要获取 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);
}
};
}
我尝试制作一个类组件:
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
”。
I need to fetch integrations info in JSON format and I need help converting useRef (functional component) to createRef(class component).
Functional component:
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);
}
};
}
I tried to make a Class component:
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>
)
}
But it throws error regarding function getIntegrations(). I guess because I didn't add 'createTTNCClient' in the class component. Here how it looks with functional component:
const TTNCClient = useRef(createTTNCClient());
but I don't know how to add 'createTTNCClient()
' to 'createRef
' in a class component.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的类组件代码似乎没有调用
createTTNCClient
构造函数。您可以在类构造函数中执行此操作:
或者在
componentDidMount
生命周期方法中执行此操作:并且作为预防措施,在尝试调用时应用一些空检查:
Your class component code doesn't appear to call the
createTTNCClient
constructor.You could probably do it there in the class constructor:
Or in the
componentDidMount
lifecycle method:And as a precaution, apply some null-checks when attempting to invoke: