2017-09-15 36 views
1

如何導出愛可信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

任何幫助嗎?

+0

'getNewQuote.call(this)' –

回答

2

可以返回從Axios公司要求的承諾,然後處理它在調用函數一樣

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) 
     }); 
    } 

或使用JavaScript .call方法調用getNewQuote功能並將this的參考文件傳遞給它,就像

componentDidMount() { 
    getNewQuote.call(this) 
    } 

    handleNewQuote() { 
    getNewQuote.call(this) 
    } 
+1

不錯!謝謝,Shubham。它的工作原理,但我不知道如何。 :) getNewQuote.call(這個)部分令人困惑:) – karolis2017

+1

閱讀這個'.call'的mdn文檔來理解它是如何工作的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call :) –

+0

@ShubhamKhatri感謝您提供的參考。 –

1

上面的答案是絕對正確的,但我想要關注的是寫幹代碼,所以這就是我的做法。

import axios from 'axios'; 
class BaseService { 
    constructor() { 
    this.baseUrl = "/api"; 
    } 

    getData(path) { 
    let url = `${this.baseUrl}${path}`; 
    return axios.get(`${url}`); 
    } 
} 

export default (new BaseService()); // singleton object 

此基本服務現在可以導入其他組件或服務。

import BaseService from './services/base.service.jsx'; 

class Home extends React.Component { 
constructor(props) { 
    super(props); 

    this.state = { 
     data: [] 
    } 

} 

componentDidMount() { 
    let path = '/users'; 
    BaseService.getData(path) 
     .then(resp => { 
      this.setState({data: resp.data}); 
     }); // handle errors if needed 
}