有人可以为我提供关于类对象的一些指导,以及如何在我的项目中的另一个对象中引用它吗?
这是我的RequestAPI对象-request-api.js(注意:我知道它还没有进行很多操作,但是我想走路之前要走路)
RequestAPI
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
Uncaught TypeError: _requestApi.RequestApi.fetch is not a function
谁能为我提供一些见识/帮助?
由于fetch不是静态方法,因此您需要先创建的实例,RequestApi然后再调用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); }); }