本文介绍了如何在javascript ES6中正确导出和导入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could someone provide me with a little bit of guidance on my class object and how to reference it in another in my project?

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

Here is my RequestAPI object - request-api.js (note: I understand that there isn't much going on in it yet, but I wanted to walk before I can run)

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组件:

Here is the React Class component that i am trying to reference it in:

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

I get an error in my React Component Class object: Uncaught TypeError: _requestApi.RequestApi.fetch is not a function

任何人都可以为我提供一些见识/帮助吗?

Can anyone provide me with some insight/assistance?

推荐答案

由于fetch不是静态方法,因此需要在RequestApi实例上创建实例,然后再调用fetch:

Since fetch is not a static method, you need to create an instance of RequestApi prior to calling fetch on it:

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

这篇关于如何在javascript ES6中正确导出和导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 16:56