【发布时间】:2025-12-07 02:35:01
【问题描述】:
我想在 typescript 中实现下面的 javascript 代码。我有一个类组件,其状态调用外部辅助方法进行修改。我需要调用 helper.ts 文件中存在的 checkAuthentication 方法并传递“this”的上下文,以及访问我的类组件中的 checkAuthentication 方法。
类组件:Home.tsx
import { checkAuthentication } from './routes/login/helper';
class Home extends React.Component<any> {
constructor(props: any) {
super(props);
console.log(props);
this.state = { authenticated: null };
this.checkAuthentication = checkAuthentication.bind(this);
}
async componentDidMount() {
this.checkAuthentication();
}
render() {
return (
<></>
)
}
}
Helper.ts 文件包含修改 Home.tsx 文件中存在的状态的 checkAuthentication 方法
async function checkAuthentication() {
const authenticated = await this.props.auth.isAuthenticated();
if (authenticated !== this.state.authenticated) {
if (authenticated && !this.state.userinfo) {
const userinfo = await this.props.auth.getUser();
this.setState({ authenticated});
} else {
this.setState({ authenticated });
}
}
}
【问题讨论】:
-
这是如何在 JavaScript 而不是在 TypeScript 中工作的? TypeScript 是 JavaScript 的类型化超集。你是说这在 TypeScript 中不适合你吗?如果它在 JS 中工作,那么它应该可以工作。
标签: reactjs typescript