【发布时间】:2018-01-31 22:02:02
【问题描述】:
我正在尝试使用 axios 从 api (https://reqres.in/) 获取数据并显示在我的反应应用程序中。在此之前,我使用 javascript 中的 fetch 方法从 API 中获取数据。现在我尝试从各种资源中对此进行编码。我该怎么做。方法正确吗?
我的 app.js 文件-
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.successShow = this.successShow.bind(this);
this.errorShow = this.errorShow.bind(this);
}
componentDidMount() {
axios.get('https://reqres.in/api/products/3')
.then(function (response) {
this.successShow(response);
})
.catch(function (error) {
this.errorShow(error);
});
}
successShow(response) {
this.member = <pre>{JSON.stringify(response.data, null, '\t')}</pre> ;
}
errorShow(error) {
this.member = <pre>{JSON.stringify(error.response.data, null, '\t')}</pre>;
}
render() {
return (
<div>
<h2>Welcome to React</h2>
<h3>{JSON.stringify(this.state.person.data)}</h3>
<div>{this.member}</div>
</div>
);
}
}
export default App;
它还给出错误 - 未处理的拒绝(TypeError):无法读取未定义的属性'errorShow'。
【问题讨论】:
-
箭头函数的关键之一是它们不会创建自己的新作用域,而是保持在当前作用域中
标签: javascript reactjs axios