【发布时间】: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