简体   繁体   中英

How to create class in one es6 module and import it in another?

I have two files: User.js and Login.js . After login is successfull i want to call static logIn method of User class. I have strange behaviour. What am I doing wrong?

File contents User.js :

// user/User.js

// I also tried export default class User
export class User { 
  static logIn (token) {
  }

  static logOut (token) {
  }

  static isAuthorized () {
  }
}

And Login.js :

// login/Login.js

import React from 'react';
import GoogleLogin from 'react-google-login';
// I also tried import User from './../user/User';
// I also tried import {User} from './../user/User';
import * as User from './../user/User';

class Login extends React.Component {

  constructor (props, context) {
    super(props, context);
  }

  responseSuccess (googleUser) {
    const idToken = googleUser.getAuthResponse().id_token;
    User.logIn(idToken);
  }

///

}

export default Login;

When I use import and export this way I get this behaviour: 在此处输入图片说明

So, User is an object with property User . This property contains all methods of class User.

Is it possible to somehow export/import class so I will get user class methods in User object?

Now there is only one way to use methods: User.User.logIn() .

You are using a default export, so with a namespace import ( * as User ) you'd have to use User.default to access the class.

Instead, use a default import:

import User from './../user/User';

However, your screenshot suggests that you're actually doing a named export with export class User { … } , not a default export. If you want to use that, you'd have to import the name:

import {User} from './../user/User'; // short for {User as User}

That said, you probably shouldn't be using a class consisting of only static methods anyway. Use multiple named exports

export function logIn(token) {
}
export function logOut(token) {
}
export function isAuthorized() {
}

and then use the namespace import

import * as User from './../user/User';

to access them as User.logIn etc.

Since you are using a default export, there is no need to specify an alias via as .

Instead, use the following syntax to import the default export of the module:

import User from './../user/User';

More info in the MDN docs .

import User from './../user/User';

should be enough, you dont have more exported values from that file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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