繁体   English   中英

如何在javascript ES6中正确导出和导入类

[英]How to export and import class properly in javascript ES6

有人可以为我提供关于类对象的一些指导,以及如何在我的项目中的另一个对象中引用它吗?

这是我的RequestAPI对象-request-api.js(注意:我知道它还没有进行很多操作,但是我想走路之前要走路)

export class RequestApi {
    constructor() {
        this.apiBase = '../api';
    }

    fetch(url, options) {
        var options = options || {};
        return fetch(this.apiBase + url, options)
            .then(_handleResponse, _handleNetworkError);
    }

    _handleResponse(response) {
        if (response.ok) {
            return response.json();
        } else {
            return response.json().then(function (error) {
                throw error;
            });
        }
    }

    _handleNetworkError(error) {
        throw {
            msg: error.message
        };
    }
}

这是我试图在其中引用的React Class组件:

import React from 'react';
import { RequestApi } from '../../../../utils/request-api.js';

class UserLayout extends React.Component {
    constructor() {
        super();
        this.state = {
            users: [],
            isLoading: true
        };
        this.addNewUser = this.addNewUser.bind(this);
        this.editUser = this.editUser.bind(this);
        this.deleteUser = this.deleteUser.bind(this);
    }
    componentDidMount() {
        return RequestApi.fetch('/user')
            .then(json => {
                this.setState({
                    isLoading: false,
                    users: json
                });
            })
            .catch(error => {
                console.error(error.msg);
            });
    }
    // more code here...
}

我在我的React Component Class对象中收到一个错误: Uncaught TypeError: _requestApi.RequestApi.fetch is not a function

谁能为我提供一些见识/帮助?

由于fetch不是静态方法,因此需要在调用fetch之前创建RequestApi的实例:

componentDidMount() {
    const api = new RequestApi();
    return api.fetch('/user')
        .then(json => {
            this.setState({
                isLoading: false,
                users: json
            });
        })
        .catch(error => {
            console.error(error.msg);
        });
}

暂无
暂无

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

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