【问题标题】:I want to manipulate the state present in React class component in a helper function. I want to achieve the same in Typescript我想在辅助函数中操作 React 类组件中存在的状态。我想在 Typescript 中实现相同的目标
【发布时间】: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


【解决方案1】:

如果它不能开箱即用(如果它在 JS 中有效,那么它应该可以,除非它是需要更改 no-implicit-this 或类似内容的类型检查错误),那么您可以执行以下操作:

function checkAuthentication(that: React.Component<any>) {
  return async function () {
    const authenticated = await that.props.auth.isAuthenticated();
    if (authenticated !== that.state.authenticated) {
      if (authenticated && !that.state.userinfo) {
        const userinfo = await that.props.auth.getUser();
        that.setState({ authenticated});
      } else {
        that.setState({ authenticated });
      }
    }
  }
}

在你的课堂上:

this.checkAuthentication = checkAuthentication(this);    

【讨论】:

    最近更新 更多