• ant.design-pro使用useModel传递全局数据


    antpro 的umi内置的useModel也可以实现全局数据流

    示例图: 三个组件的数量可以共享
     
    使用方法
    在src目录下models文件夹,新建一个文件,文件名就是引入的数据对象

    1.
     
    2.
     
    完整代码
    /src/models/product.ts
    import { useState, useCallback } from 'react'
    
    export default () => {
      const [count, setCount] = useState(0)
    
      // 增加数量
      const addCount = useCallback((val: number = 1) => {
        setCount((pre) => { return pre + val })
      }, [])
    
      // 减少数量
      const substractCount = useCallback((val: number = 1) => {
        setCount((pre) => { return pre - val })
      }, [])
    
      return {
        count,
        addCount,
        substractCount
      }
    }
    组件中使用
    组件1
    /src/pages/components1
    import React from 'react';
    import { useModel } from 'umi';
    import { Descriptions, Button } from 'antd';
    
    export default () => {
      const { count, addCount, substractCount } = useModel('product', model => (
        { 
          count: model.count, 
          addCount: model.addCount,
          substractCount: model.substractCount,
        }
      ))
    
      return <>
        <h2>页面一</h2>
        <Descriptions title="商品信息">
          <Descriptions.Item label="名称">T-shirt</Descriptions.Item>
          <Descriptions.Item label="价格">799</Descriptions.Item>
          <Descriptions.Item label="数量">{count}</Descriptions.Item>
        </Descriptions>
        <h2>修改数据</h2>
        <Button type="primary" onClick={() => addCount()} style={{marginRight: '10px'}}>
          数量+1
        </Button>
        <Button type="primary" onClick={() => substractCount()}>
          数量-1
        </Button>
      </>
    };
    组件2
    /src/pages/components2
    import React from 'react';
    import { useModel } from 'umi';
    import { Descriptions, Button } from 'antd';
    
    export default () => {
      const { count, addCount, substractCount } = useModel('product', model => (
        { 
          count: model.count, 
          addCount: model.addCount,
          substractCount: model.substractCount,
        }
      ))
    
      return <>
        <h2>页面二</h2>
        <Descriptions title="商品信息">
          <Descriptions.Item label="名称">T-shirt</Descriptions.Item>
          <Descriptions.Item label="价格">799</Descriptions.Item>
          <Descriptions.Item label="数量">{count}</Descriptions.Item>
        </Descriptions>
        <h2>修改数据</h2>
        <Button type="primary" onClick={() => {addCount(2)}} style={{marginRight: '10px'}}>
          数量+2
        </Button>
        <Button type="primary" onClick={() => {substractCount(2)}}>
          数量-2
        </Button>
      </>
    };
  • 相关阅读:
    es6-字符串常用方法
    新增行数据校验
    python-Django路由传参
    递归算法
    CSS动画效果
    克隆远程仓库
    添加git仓库
    滚动条——overflow:auto 自定义样式
    CSS——链接伪类选择器
    进程,线程,同步 ,异步
  • 原文地址:https://www.cnblogs.com/steamed-twisted-roll/p/15207327.html
Copyright © 2020-2023  润新知