在create-react-app搭建的框架中mock数据方法

环境:

1.用create-react-app搭建的React的应用
2.没有用npm run eject弹出默认config

采用的插件:

json-server :用于模拟后端的各种请求;
concurrently:用于并发地启动我们前端的web server和后端的server;

使用步骤

1.npm install json-server concurrently
2.在根目录下创建mock文件夹,在mock文件夹下创建文件db.json

其中db.json文件内容如下(以表格数据为例):


屏幕快照 2019-02-27 下午7.51.26.png
3.在根目录下创建utils文件夹,在其下创建request.ts,主要处理封装请求,导出request 作为公共方法,代码如下:
import fetch, { AxiosResponse, AxiosRequestConfig, CancelTokenSource } from 'axios';
import { message } from 'antd';
import { stringify } from 'qs';
// import config from './config';

// const { apiPrefix } = config;

function checkStatus(response: AxiosResponse) {
  if (response.status >= 200 && response.status < 300) {
    return response.data;
  }
  const msg = response.data.message ? response.data.message : '接口格式返回错误';
  message.error(msg);
  const error = Object.assign(new Error(`${response.statusText}:${msg}`), {
    response
  });
  throw error;
}

function checkData(response: { status: boolean, message: string, data: Object }): any {
  if (response.status === true) {
    return response;
  }
  if (response.message) {
    message.error(response.message);
  } else {
    const error = Object.assign(new Error(response.message || '请求失败'), {
      response
    });
    throw error;
  }
  return;
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(
  url: string,
  options?: { method?: 'GET' | 'POST', body?: Object, [key: string]: any },
  withCredentials: boolean = true,
  withApiPrefix: boolean = true,
  cancleSource?: CancelTokenSource,
) {
  const method = (options && options.method) ? options.method.toUpperCase() : 'GET';
  const requestOption: AxiosRequestConfig = {
    // url: withApiPrefix ? `${apiPrefix}${url}` : url,
    url: url,
    method,
    withCredentials,
    validateStatus(status: number) {
      return status < 500;
    },
    paramsSerializer(params: Object) {
      return stringify(params, { arrayFormat: 'indices' });
    },
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  };

  if (options) {
    if (method === 'GET') {
      requestOption.params = options.body || options;
    } else {
      if (options.body) {
        requestOption.data = options.body;
      }
    }
  }

  if (cancleSource) {
    requestOption.cancelToken = cancleSource.token;
  }

  return fetch(requestOption)
    .then(checkStatus)
    .then(checkData)
    .then(data => ({ ...data }))
    .catch((err) => {
      throw err;
    });
}

4.修改package.json文件,主要代码如下:

"scripts": {
    "start": "concurrently 'react-app-rewired start --scripts-version react-scripts-ts' 'json-server --watch ./mock/db.json -p 3001'",
    "build": "react-app-rewired build --scripts-version react-scripts-ts",
    "test": "react-app-rewired test --env=jsdom --scripts-version react-scripts-ts"
  },

"proxy": {
    "/": {
      "target": "http://localhost:3001"
    }
  }

5.调用接口:

 request(props.url).then((res: any) => {
          this.setState({
            dataSource: res.data
          });
        });

实现思路参考如下文章:
https://cuyu.github.io/javascript/2017/04/21/%E6%89%93%E9%80%A0%E5%8F%AF%E4%B8%8E%E5%90%8E%E7%AB%AF%E6%97%A0%E7%BC%9D%E8%A1%94%E6%8E%A5%E7%9A%84%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83

你可能感兴趣的:(在create-react-app搭建的框架中mock数据方法)