美文网首页
react --- 数据监听、axios请求封装

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

作者: 再回首已落幕 | 来源:发表于2021-03-17 17:48 被阅读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);
      }
    

    相关文章

      网友评论

          本文标题:react --- 数据监听、axios请求封装

          本文链接:https://www.haomeiwen.com/subject/hepecltx.html