sca*_*t17 4 javascript ecmascript-6 reactjs
有人可以为我提供有关我的类对象以及如何在我的项目中的另一个对象中引用它的一些指导吗?
这是我的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
};
}
}
Run Code Online (Sandbox Code Playgroud)
这是我试图在其中引用它的 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...
}
Run Code Online (Sandbox Code Playgroud)
我的 React Component Class 对象出现错误: Uncaught TypeError: _requestApi.RequestApi.fetch is not a function
任何人都可以为我提供一些见解/帮助吗?
由于fetch不是静态方法,您需要RequestApi在调用fetch它之前创建一个实例:
componentDidMount() {
const api = new RequestApi();
return api.fetch('/user')
.then(json => {
this.setState({
isLoading: false,
users: json
});
})
.catch(error => {
console.error(error.msg);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6415 次 |
| 最近记录: |