【问题标题】:Invalid hook call. Is it possible to call hooks or async functions outside body of function component?无效的挂钩调用。是否可以在函数组件的主体之外调用钩子或异步函数?
【发布时间】:2021-12-08 18:52:33
【问题描述】:

有没有办法在不将我的功能组件更改为基于类的组件的情况下完成这项工作:

export default function SendVerificationCode({
  route,
  navigation
}: NativeStackScreenProps<
  NativeStackParameterList,
  'SendVerificationCode'
>): JSX.Element {

  async function getVerificationCode(
    passwordApi: PasswordApi,
    agencyKey: number,
    username: string,
    email: string,
    verificationCode: string
  ): Promise<void> {
    const response = await passwordApi.getReset(
      new GetResetRequest({
        agencyKey: agencyKey,
        email: email,
        username: username,
        verificationCode: verificationCode
      })
    );

    verifyCodeContext.userName = username;
    navigation.navigate('VerifyCode', {
      copyrightYear: 2021,
      version: '0.0.0.1'
    });
  }

  const onSubmit = (data: any) => {
    getVerificationCode(
      new PasswordApi(),
      1234,
      data.username,
      data.email,
      '123'
    );
  };

  return (
    <UnauthenticatedTemplate copyrightYear={year} version={version}>
      <Form
        style={styles.form}
        submitText="Send Code"
        onSubmit={onSubmit}
        schema={SendVerificationCodeSchema}
      >
        <FCTextField name="username" placeholder="Username" />
        <FCTextField name="email" placeholder="Email" />
      </Form>
    </UnauthenticatedTemplate>
  );
}

在我打电话给getVerificationCode之前,onSubmit 工作得很好

我的 axios 函数 getReset 看起来像:

public getReset(
    getResetRequest: GetResetRequest,
    cancelToken?: CancelToken
  ): Promise<StandardResponse<GetResetResponse>> {
    return this.get(
      this.configuration.portal,
      '/mvc/api/password/reset',
      classToPlain(getResetRequest, BaseApi.classTransformOptions),
      cancelToken,
      new StandardResponse<GetResetResponse>(GetResetResponse)
    );
  }

【问题讨论】:

  • 拨打getVerificationCode会发生什么?
  • 可能的未处理承诺拒绝(id:1):错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用
  • 应用程序不会崩溃,但会发出警告,并且网络请求 getVerificationCode 永远不会被调用
  • 一个问题,当你使用jsx元素时,你是在导入react吗?
  • 是的,我正在使用反应导入。我的反应导入不是问题。

标签: javascript reactjs typescript react-native ecmascript-6


【解决方案1】:

在你的应用程序的某个地方,你在一个不是 React 组件的函数中调用了一个钩子(以 use 开头的函数,例如 useState),我认为问题不在于代码 sn-ps 你'已经包括在内,也许问题出在您要导航到的屏幕上?

检查您的代码并查找钩子并确保它们不在函数中,示例:

// Right implementation
function SomeComponent(props) {
  const hook = useHook()
  return <View />
}

// Wrong implementation
function SomeComponent(props) {
  function nestedFunction() {
    const hook = useHook()
  }
  return <View />
}

希望对您有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2022-11-27
    • 2019-11-21
    • 2020-10-27
    • 2021-10-31
    • 1970-01-01
    • 2019-11-01
    相关资源
    最近更新 更多