2017-09-15 56 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 
}