首页 > 解决方案 > 无效的挂钩调用。是否可以在函数组件的主体之外调用钩子或异步函数?

问题描述

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

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>
  );
}

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

我的 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)
    );
  }

标签: javascriptreactjstypescriptreact-nativeecmascript-6

解决方案


在您的应用程序的某个地方,您在不是 React 组件的函数中调用了一个钩子(以 use 开头的函数,例如 useState),我认为问题可能不在您包含的代码片段中问题出在您要导航到的屏幕上?

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

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

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

希望你觉得这有帮助


推荐阅读