【问题标题】:How to export and import class properly in javascript ES6如何在javascript ES6中正确导出和导入类
【发布时间】:2018-02-23 18:25:12
【问题描述】:

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

这是我的 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 组件类对象出现错误:Uncaught TypeError: _requestApi.RequestApi.fetch is not a function

谁能给我一些见解/帮助?

【问题讨论】:

  • 试试var requestApi = new RequestApi(); requestApi.fetch()
  • 类通常需要实例化。如果你不想这样,那么导出一个简单的对象而不是一个类。

标签: javascript reactjs ecmascript-6


【解决方案1】:

由于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);
        });
}

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多