如何導出愛可信get請求從不同的js文件,所以我可以通過導入即使用它在我main.js:愛可信GET請求功能導出/導入反應
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: Cannot read property 'setState' of undefined at api.js:8 at
我認爲這個問題是:
個愛可信getNewQuote出口或getNewQuote呼叫componentDidMount
任何幫助嗎?
'getNewQuote.call(this)' –