【问题标题】:axios GET request function export/ import in reactaxios GET请求功能导出/导入反应
【发布时间】:2018-02-24 04:44:00
【问题描述】:

如何从单独的 .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:无法读取未定义的属性“setState” 在 api.js:8 在

我认为问题出在:

componentDidMount 中的axios getNewQuote 导出或getNewQuote 调用

有什么帮助吗?

【问题讨论】:

  • getNewQuote.call(this)

标签: reactjs axios


【解决方案1】:

您可以从 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)
      });
  }

或使用Javascript .call 方法调用getNewQuote 函数并将this 的引用传递给它,就像

 componentDidMount() {
    getNewQuote.call(this)
  }

  handleNewQuote() {
    getNewQuote.call(this)
  }

【讨论】:

  • 不错!谢谢,舒巴姆。它有效,但我不知道如何。 :) getNewQuote.call(this) 部分令人困惑:)
  • 阅读 .call 的这个 mdn 文档以了解它是如何工作的 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… :)
  • @ShubhamKhatri 感谢您提供的参考。
  • 很高兴有帮助:)
【解决方案2】:

上面的答案是绝对正确的,但是我要重点写的是干代码,所以我就是这样做的。

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
}

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2021-07-15
    • 1970-01-01
    • 2020-12-26
    • 2021-09-24
    • 2021-06-18
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多