axios GET请求功能在反应中导出/导入

kar*_*017 3 reactjs axios

如何从单独的.js文件导出axios获取请求,以便可以通过导入ie在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();
  }
   ...
Run Code Online (Sandbox Code Playgroud)

我的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)
      })
}
Run Code Online (Sandbox Code Playgroud)

通过此设置,我在控制台中遇到错误:

TypeError:无法读取api.js:8处未定义的属性“ setState”

我认为问题在于:

axios getNewQuote导出或componentDidMount中的getNewQuote调用

有什么帮助吗?

Shu*_*tri 6

您可以从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')
}
Run Code Online (Sandbox Code Playgroud)

并像

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)
      });
  }
Run Code Online (Sandbox Code Playgroud)

getNewQuote使用Javascript .call方法调用该函数并将其引用传递this给它,例如

 componentDidMount() {
    getNewQuote.call(this)
  }

  handleNewQuote() {
    getNewQuote.call(this)
  }
Run Code Online (Sandbox Code Playgroud)

  • 阅读 `.call` 的这个 mdn 文档以了解它是如何工作的 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call :) (2认同)