如何从单独的.js文件导出axios获取请求,以便可以通过导入ie在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:无法读取api.js:8处未定义的属性“ setState”
我认为问题在于:
axios getNewQuote导出或componentDidMount中的getNewQuote调用
有什么帮助吗?
您可以从axios请求中返回promise,然后在调用函数中进行处理,例如
export function getNewQuote(){
axios.defaults.baseURL = 'https://andruxnet-random-famous-quotes.p.mashape.com';
axios.defaults.headers.common['X-Mashape-Key'] = "MY-API-KEY";
return axios.get('/?cat=famous&count=1')
}
并像
componentDidMount() {
getNewQuote().then(res => {
this.setState({ quote: res.data })
})
.catch(error => {
console.log(error)
});
}
handleNewQuote() {
getNewQuote().then(res => {
this.setState({ quote: res.data })
})
.catch(error => {
console.log(error)
});
}
或getNewQuote
使用Javascript.call
方法调用该函数并将其引用传递this
给它,例如
componentDidMount() {
getNewQuote.call(this)
}
handleNewQuote() {
getNewQuote.call(this)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句