繁体   English   中英

在Component中调用react类的方法

[英]Calling a method of a react class in a Component

我正在按照https://auth0.com/blog/adding-authentication-to-your-react-flux-app//的教程在我的reactjs应用程序中实现登录身份验证

我已经编写了一个名为AuthService的类,并且在AuthService内部有一个函数调用Login,如下所示

import LoginActions from './LoginAction';
const URL_LOGIN = 'loginurl';
class AuthService {
   login(username, password) {
     // do something
  }
}

现在,我在我的登录组件中调用此Login方法,如下所示

//this function is to save data to the API
loginUser = (user) => {
  // Here, we call an external AuthService.
    Auth.login(user.username, user.password)
    .catch(function(err) {
      console.log("Error logging in", err);
      console.log(err);
    });

一切都很好,但是当我提交数据时,我得到了错误

TypeError: WEBPACK_IMPORTED_MODULE_4__authentication_AuthService .a.login(...)未定义

当我在AuthService类的login方法上控制台日志时,我看到了返回的数据。 我一直在寻找针对此错误的快速解决方案,但还没有得到。 任何帮助,将不胜感激。 我不想将此操作带到组件上,因为我还将在应用程序的其他区域中使用它。

另外,我是Reactjs的新手,因为这是我在这里进行的第一个身份验证。

在AuthService类的login方法之前添加static关键字。

我正在等待djfdev看到他的评论中的答案:

您已将login定义为实例方法,但像静态方法一样调用它。 在函数名称前添加static关键字,或在调用login之前创建Auth实例。

但似乎他没有提供答案。 他的意思是您可以定义一个静态方法,例如:

static login(username, password) {

或在以下实例中调用登录方法:

const auth = new Auth
auth.login(user.username, user.password)

此外,我希望您导出的类如下:

export default AuthService

并像这样导入:

import Auth from '...'

根据我对OP的评论:

您已将login定义为实例方法,但像静态方法一样调用它。 在函数名称前添加static关键字,或在调用login之前创建Auth实例。

因此,您有两个选择:A)使用static关键字在类本身上定义您的方法:

import LoginActions from './LoginAction';
const URL_LOGIN = 'loginurl';
class AuthService {
   static login(username, password) {
     // do something
  }
}

或B)在调用登录方法之前创建Auth实例:

loginUser = (user) => {
  // Here, we call an external AuthService.
  new AuthService().login(user.username, user.password)
    .catch(function(err) {
      console.log("Error logging in", err);
      console.log(err);
  });

请参阅MDN文档以获取static

我通过将静态方法添加到登录方法中(作为上述建议)并从中删除了问题来解决了这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM