Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

reactjs - How to export and import class properly in 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?

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
        };
    }
}

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...
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...