美文网首页
react之Ant Design Pro系列快速入门(五)--拉

react之Ant Design Pro系列快速入门(五)--拉

作者: 子木话 | 来源:发表于2019-10-10 10:34 被阅读0次

1、src/routes 中新建一个最简单的页面组件 Ruirui

2、src/common/router 中新建一个不需要新 layout 的路由(这样就可以依托于pro初始化已经建好的layout组件),比如:

 '/dashboard/ruirui': {
    component: dynamicWrapper(app, ['ruirui'], () => import('../routes/Ruirui')),
 },

此处的 '/dashboard/ruirui' 是路由url页面地址,
'ruirui'指的是与页面一起加载的 model ,
import('../routes/Ruirui') 自然指的就是页面组件了。

3、src/models 中新建一个 model ,名叫 ruirui (就是第二步中与页面一起加载的),内容如下:

  import { queryInterests } from '../services/api';
 
  export default {
    namespace: 'ruirui',//全局state名称,要独一无二,会在页面组件的 connect 中使用
 
    state: {
      interests: [],//会在页面中类似这样使用 this.props.ruirui.interests
    },
 
    effects: {
      *queryInterests(_, { call, put }) {//这里的 queryInterests 是在页面组件的 dispatch 中使用的
        const response = yield call(queryInterests);//这里的 queryInterests 是调用的api接口
        yield put({
          type: 'interestsSuccessful',//能匹配到下方 reducers 中的任意一个方法
          payload: response,
        });
      },
    },
 
    reducers: {
      interestsSuccessful(state, action) {
        return {
          ...state,
          interests: action.payload,
        };
      },
    },
  };

4、第三步中的 queryInterests api接口实际上我们还没有创建,现在去创建

进入 src/services/api ,新增接口内容如下:

export async function queryInterests() {
  return request('/api/interests');
}

这里的 '/api/interests' 是什么?请看第五步。(如果你需要请求后台接口,就直接请求接口,不需要第五步)

5、先在 mock 文件夹中增加 interests 文件,文件写入如下内容:

export const getInterests = (req, res) => {
  res.json(['看电影','读书','天马行空','做梦','学习不会的事情']);
};
export default {
  getInterests,
};

然后进入 根目录的 .roadhogrc.mock.js 文件,增加:

import { getInterests } from './mock/interests';

并在 proxy 中增加

  GET /api/interests': getInterests,

6、最后,我们进入页面组件Ruirui 去请求数据,内容如下:

import React, { Component } from 'react';
import { connect } from 'dva';
@connect(({ ruirui, loading }) => ({//将 routers 中设置的页面组件和 model 真正的关联起来,请注意与namespace名称一致!
  ruirui,
  loading: loading.models.monitor,
}))
export default class Ruirui extends Component {
  componentDidMount() {
    this.props.dispatch({
      type: 'ruirui/queryInterests',
    });
  }
  render() {
    const {interests} = this.props.ruirui;
    console.log( interests );
    
    return (
      <div>
        Ruirui
      </div>
    );
  }
}

总结:

1、一个页面可以使用多个 model ,一个 model 可以被多个页面使用,他们是多对多的关系。
2、页面绑定 model 时,请注意 connect 中参数的名称与 namespace 保持一致。

相关文章

网友评论

      本文标题:react之Ant Design Pro系列快速入门(五)--拉

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