axios GET 请求函数导出/导入反应

axios GET request function export/ import in react

如何从单独的 .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: Cannot read property 'setState' of undefined at api.js:8 at

我认为问题在于:

axios getNewQuote 导出或在 componentDidMount 中调用 getNewQuote

有什么帮助吗?

你可以return 来自 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)
  }

上面的回答是完全正确的,但是我想专注于编写干代码,所以我就是这样做的。

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
}