示例图: 三个组件的数量可以共享 使用方法 在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> </> };