react --- 数据监听、axios请求封装

2021-03-17  本文已影响0人  再回首已落幕

一、数据监听

constructor(props) {
    super(props);
    this.state = {
      name: "张三",
      data: "123",
    };
  }

<button onClick={() => { this.setState({ data: 6666 }); }} > 触发监听 </button>

componentDidUpdate(i,j) {
    console.log(i);
    console.log(j)
    console.log(this.props);
    console.log(this.state);
  }

控制台输出:


image.png

二、axios请求封装
新建server.js

import axios from "axios";
// import qs from "qs";
axios.defaults.baseURL = "http://1.111.111.113:8000";
axios.interceptors.request.use((config) => {
//   console.log(config);
  return config;
});

axios.interceptors.response.use((config) => {
//   console.log(config);
  return config;
});

const http = {
  post: "",
  get: "",
};

http.post = function (api, data) {
  //let params = qs.stringify(data);
  return new Promise((resolve, reject) => {
    axios.post(api, data).then((response) => {
      resolve(response);
    });
  });
};

http.get = function (api, data) {
  //let params = qs.stringify(data);
  return new Promise((resolve, reject) => {
    axios.get(api, data).then((response) => {
      resolve(response);
    });
  });
};

export default http;

index.js

import http from './server'
React.$http = http

使用

async componentDidMount() {
    const { data: res } = await React.$http.post("/getBag", { params: 111 });
    console.log(res);
  }
上一篇 下一篇

猜你喜欢

热点阅读