dva中mockjs和fetch基本使用

在构建好的dva框架中直接在mock里面设置自己想要的js数据模拟接口模块,比如:
mock/goodsList.js
get的请求

const Mock = require("mockjs");
module.exports = {
  "GEt /api/goods/list": (req, res) => {
    res.status(200).json(
      Mock.mock({
        "data|10-30": [
          {
            type: "小说",
            name: "莫泊桑小说",
          },
          {
            type: "历史",
            name: "秦皇治国史册",
          },
          {
            type: "文学",
            name: "朱自清散文集",
          },
        ],
        code: 0,
        message: "sucess",
      })
    );
  },
};

post的请求

const Mock = require("mockjs");
module.exports = {
  "POST /api/goods/list": (req, res) => {
    res.status(200).json(
      Mock.mock({
        "data|10-30": [
          {
            type: "小说",
            name: "莫泊桑小说",
          },
          {
            type: "历史",
            name: "秦皇治国史册",
          },
          {
            type: "文学",
            name: "朱自清散文集",
          },
        ],
        code: 0,
        message: "sucess",
      })
    );
  },
};

.roadhogrc.mock.js文件中引入mock请求接口

// 第一种方式引入mock文件
// export default {
//   ...require("./mock/goods"),
//   ...require("./mock/goodList"),
// };
// 第二种方式引入mock文件
import fs from "fs";
import path from "path";

const mock = {};
fs.readdirSync(path.join(__dirname + "/mock")).forEach(function (file) {
  if (file.match(/\.js$/)) {
    Object.assign(mock, require("./mock/" + file));
  }
});
export default mock;

api.js 需要请求接口的url

import request from "../utils/request";

export function goodsList() {
  return request("/api/goods/list");
}

export function goodsList2() {
  return request("/api/goods/list", { method: "post" });
}

fetch请求集成和简单封装
utils/request.js

import fetch from "dva/fetch";
import qs from "querystring";

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function handleHeaders(options) {
  const headers = options.headers || {};
  const defaultHeaders = {
    "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  };
  options.headers = Object.assign({}, defaultHeaders, headers);

  if (options.method === "post") {
    let body = options.body || {};
    body = qs.stringify(body);
    options.body = body;
  }
}

/**
 * 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 function request(url, options = {}) {
  //get请求
  if (!options.method || options.method === "get") {
    url += `?${qs.stringify(options.params)}`;
  }

  //处理头部
  handleHeaders(options);

  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((data) => ({ data }))
    .catch((err) => ({ err }));
}

将数据接口当做公共接口,在dva/redux中调用
在路径models\goodList.js

import { goodsList } from "../services/example";
export default {
  namespace: "goodList",
  state: {
    goodsList: [
      {
        type: "小说",
        name: "莫泊桑小说",
      },
      {
        type: "历史",
        name: "秦皇治国史册",
      },
      {
        type: "文学",
        name: "朱自清散文集",
      },
    ],
  },
  //处理网络请求
  effects: {
    //请求接口 页面需要用的话直接使用dispatch调用方法名即可
    *updateListHttp({ payload }, { call, put }) {
      // yield put({ type: "save" });
      //异步请求goodsList2接口数据
      const result = yield call(goodsList, payload);
      const data = result.data.data;
      //yield put触发reducers的updateList方法 内部触发dispatch
      if (data) {
        yield put({
          type: "updateList",
          payload: data,
        });
      }
    },
  },
  reducers: {
    updateList(state, action) {
      const newState = JSON.parse(JSON.stringify(state));
      //数据为数组是网络请求需要更新数据
      if (action.payload instanceof Array) {
        newState.goodsList = action.payload;
      } else {
        //数据为对象是操作数据 直接push
        newState.goodsList.push(action.payload);
      }

      return newState;
    },
  },
};

组件使用dispatch调用接口 需要触发effects里面的updateListHttp方法 需要使用dispatch触发一下。

 componentDidMount() {
    //请求接口更新数据
    this.props.dispatch({
      type: "goodList/updateListHttp",
      payload: {},
    });
  }

你可能感兴趣的:(react,reactjs)