antd pro如何请求数据

### 以新建一个页面( Susu ) ,新建一个model ( Susu ),且该页面使用该 model 为例。

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

2、src/common/router 中新建一个不需要新 layout 的路由(这样就可以依托于pro初始化已经建好的layout组件),比如:
```
  '/dashboard/susu': {
    component: dynamicWrapper(app, ['susu'], () => import('../routes/Susu')),
  },
```
此处的 '/dashboard/susu' 是页面地址,'susu'指的是与页面一起加载的 model ,import('../routes/Susu') 自然指的就是页面组件了。

3、src/models 中新建一个 model ,名叫 susu (就是第二步中与页面一起加载的),内容如下:
```
  import { queryInterests } from '../services/api';

  export default {
    namespace: 'susu',//全局state名称,要独一无二,会在页面组件的 connect 中使用

    state: {
      interests: [],//会在页面中类似这样使用 this.props.susu.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、最后,我们进入页面组件 Susu 去请求数据,内容如下:
```
import React, { Component } from 'react';
import { connect } from 'dva';

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




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

猜你喜欢

转载自blog.csdn.net/RuiKe1400360107/article/details/82348602