react 中axios的引用方法

一。在组件中引用

组件
import React, { Component } from 'react';
import './index.css';
import axios from 'axios';


class Login extends Component {
  constructor(props) {
    super(props);
  }
  //当组件输出到 DOM 后会执行 componentDidMount()
  componentDidMount() {
    const _this = this; //先存一下this,以防使用箭头函数this会指向我们不希望它所指向的对象。
    axios
      .get("/api/login")
      .then((response) => {
          console.log(response.data);
        _this.setState({
          users: response.data,
          isLoaded: true
        });
      })
      .catch(function(error) {
        console.log(error);
        _this.setState({
          isLoaded: false,
          error: error
        });
      });
  }

  render() {
    return 
login
; } } export default Login;

二。添加到React原型上

在index.js入口问价中添加

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import axios from "axios";

React.Component.prototype.axios = axios;

ReactDOM.render(, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

在组件中使用

import React, { Component } from 'react';
import './index.css';
// import axios from 'axios';


class Login extends Component {
  constructor(props) {
    super(props);
  }
  //当组件输出到 DOM 后会执行 componentDidMount()
  componentDidMount() {
    const _this = this; //先存一下this,以防使用箭头函数this会指向我们不希望它所指向的对象。
    this.axios
      .get("/api/login")
      .then((response) => {
          console.log(response.data);
        _this.setState({
          users: response.data,
          isLoaded: true
        });
      })
      .catch(function(error) {
        console.log(error);
        _this.setState({
          isLoaded: false,
          error: error
        });
      });
  }

  render() {
    return 
login
; } } export default Login;

 

你可能感兴趣的:(react)