Lufer

  • 首页
  • 编程
  • 学习笔记
  • 日常折腾
Lufer
Code the World
  1. 首页
  2. 编程
  3. 前端
  4. 正文

AntDesign Pro V5 到底怎么用之plugin-model

2021年8月5日 1294点热度 1人点赞 0条评论

在AntDesign Pro v5中,抛弃了先前的Dva,不再使用原先的数据流方案,而是使用了@umijs/plugin-model。

官方网址见:https://umijs.org/zh-CN/plugins/plugin-model

创建Model

在src/models下面创建model文件,按照官方的说法,只要创建的model符合hooks model的规范,就可以自动检测到,文件名则对应最终 model 的 name。
这里我们新建一个叫做IdentityModelTest.js的文件。

import { useState, useCallback } from 'react'
//这是我自己写的一个request请求函数,具体可见另一篇关于useRequest的介绍。
import { GetPersonIdentityBySearch } from '@/services/ant-design-pro/api';
import { useRequest } from '@umijs/hooks';

export default function IdentityModelTest() {
  //创建一个名为Identity的State,并配套一个setIdentity的方法用于更新State。
  const [Identity,setIdentity] = useState(null);
  //这是一个发起请求的手动触发函数,并在成功后通过setIdentity更新了State。
  const { loading, run } = useRequest(GetPersonIdentityBySearch,{
    manual: true,
    onSuccess: (result, params) => {
      setIdentity(result);
    }
  });
  //定义一个方法searchIdentity,并传入参数conditions。
  const searchIdentity = useCallback((conditions) => {
    run(conditions);
  }, [])
  //决定了向外暴露的值和方法。
  return {
    Identity,
    searchIdentity,
  }
}

其实这个model和Dva时期的model功能上来讲都差不多,定义state,通过操作更改state,只不过把fetch和reducer改成了useRequest和setState。

使用Model

有了Model之后,就可以在具体的业务场景中进行消费使用,并且在model的state更新之后,也会同步触发页面的更新。

//引入useModel才能使用model
import { useModel } from 'umi';
export default () => {
    //通过useModel('Model名')来使用Model,并解构其暴露出来的值或方法。
    const { Identity,searchIdentity} = useModel('IdentityModelTest');  
    //此时就可以通过暴露出来的接口传参并执行相关的业务逻辑。
    searchIdentity(value);
    //Identity也可以直接使用。
标签: AntDesign plugin-model React UmiJS
最后更新:2023年7月10日

Lufer

新的一天开始啦

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

文章目录
  • 创建Model
  • 使用Model

COPYRIGHT © 2022 lufer.cc.

Theme Kratos Made By Seaton Jiang

鲁ICP备2021045819号