当前位置: 首页 > 面试题库 >

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

范豪
2023-03-14
问题内容

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

这是我的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不是静态方法,因此您需要先创建的实例,RequestApi然后再调用fetch它:

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


 类似资料:
  • 注意:我知道有很多关于这个主题的帖子,我已经审阅了相当多的没有成功(请看我在这篇文章底部的参考资料)。 我正试图使用Visual Studio代码在TypeScript中运行一个非常简单的测试,其中我在一个文件中声明一个类并将其导入到另一个文件中。但是,我仍然遇到一个问题,我正在导入的文件无法识别我从另一个文件导出的类的方法。 此时我收到的确切错误消息是: [ts]属性“Get FirstName

  • 我正在尝试导入一个jar文件。我的文件“test.java”包含一行: 注意:我使用的是Mac电脑。

  • 我试图通过手动将图像拖到eclipse或导入来解决这个问题。但正如下图所示,这些图像总是碰巧是一个文本文件。请帮忙! 放大,你可以看到导入的图像是一个文本文件,在这里输入图像描述 当我打开它: 在此输入图像描述

  • 问题内容: 在我用Go编写的Google App Engine项目中,我一直在使用例如 在很长一段时间内都取得了成功,并假设导入将我拥有App Engine SDK的地方定位。但是,现在我也想使用Google的第三方库,该库也使用App Engine的东西,但是要以完整路径导入: 运行应用 未能找到appengine失败: 显然,我希望使用相同的App Engine部件来避免其他问题。我的第一步是

  • 如何通过查询导入和导出.sql文件。在jdbc中使用的注意事项

  • 导出(export)和导入(import)指令有几种语法变体。 在上一节,我们看到了一个简单的用法,现在让我们来探索更多示例吧。 在声明前导出 我们可以通过在声明之前放置 export 来标记任意声明为导出,无论声明的是变量,函数还是类都可以。 例如,这里的所有导出均有效: // 导出数组 export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug',