【发布时间】:2018-02-24 04:44:00
【问题描述】:
如何从单独的 .js 文件导出 axios get 请求,以便我可以通过导入在我的 main.js 中使用它,即:
import { getNewQuote } from './api'
class App extends Component {
constructor () {
super();
this.state = {
quote: []
}
this.handleNewQuote = this.handleNewQuote.bind(this);
}
componentDidMount() {
getNewQuote();
}
handleNewQuote() {
getNewQuote();
}
...
我的 api.js 看起来像这样:
export function getNewQuote(){
axios.defaults.baseURL = 'https://andruxnet-random-famous-quotes.p.mashape.com';
axios.defaults.headers.common['X-Mashape-Key'] = "MY-API-KEY";
axios.get('/?cat=famous&count=1')
.then(res => {
this.setState({ quote: res.data })
})
.catch(error => {
console.log(error)
})
}
使用此设置,我在控制台中遇到错误:
TypeError:无法读取未定义的属性“setState” 在 api.js:8 在
我认为问题出在:
componentDidMount 中的axios getNewQuote 导出或getNewQuote 调用
有什么帮助吗?
【问题讨论】:
-
getNewQuote.call(this)