【问题标题】:How to wrap with a function a component which exports a factory?如何用函数包装导出工厂的组件?
【发布时间】:2021-09-25 12:08:53
【问题描述】:

在我的 reactjs 应用程序中,我成功使用了一个返回工厂的组件(我认为这是正确的名称)。
简而言之:

import { Auth } from "authenticator";


export default function SignIn() {
  ...
  const signIn = (e) => {
    Auth.signIn({username, password}).then((user) => {
       ...
    });
  }
}

如您所见,工厂函数返回承诺。
现在,我想用一个函数来包装 Auth 工厂,比如说一个油门。
因此,为了避免包装每个 Auth 函数调用(Auth.signIn、Auth.signUp、Auth.forgotPassword 等),我想将 Auth 组件包装在我的另一个组件中。
像这样的想法:

import { Auth } from "authenticator";
import { throttle } from "throttle";   

export default function ThrottledAuth() {
  return throttle(Auth);
}

当然,这个解决方案的问题是我不能像我希望的那样做:

import ThrottledAuth from "./ThrottledAuth";

ThrottledAuth.signIn({username, password)}).then((user) => {
    ...
});

因为我得到:“Uncaught TypeError: promise.then is not a function”,因为 Auth.signIn 返回一个 promise。

您能否建议包装工厂返回函数(返回承诺)的正确方法?

【问题讨论】:

  • 不要使用throttledAuth,而是尝试使用单独的throttled method,不要使用throttle(Auth),尝试使用throttle(Auth.signIn)。但这里再次需要对油门实现进行微调
  • 我已经尝试过throttle(Auth.signIn),但得到了:Uncaught TypeError: Object(...)(...).then is not a function。而且我无法调整油门,它是一个外部模块。

标签: javascript reactjs react-functional-component


【解决方案1】:

我自己终于找到了这个解决方案,我完全不喜欢它,因为它很枯燥......

export async function throttledSignIn(props, {success, error, final}) {
  throttle(
    Auth.signIn({...props})
      .then((result) => success(result))
      .catch((data) => error(data))
      .finally((data) => final(data))
   );
}

这样使用:

import { throttledSignIn, throttledSignUp, ... } from "./ThrottledAuth";

throttledSignIn({
  username,
  password,
}, {
  success: (user) => {
    ...
  },
  error: (err) => {
    ...
  },
  final: (data) => {
    ...
  }
});

我不会接受这个答案,如果有更时尚的解决方案,我会很高兴阅读并采用它...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2021-09-24
    • 2022-06-30
    相关资源
    最近更新 更多