AntDesign Pro connect

DVA中connect方法与Model数据交互实践
本文介绍了DVA框架中connect方法的使用,用于在React组件中获取Model中的数据。通过connect可以将Model的state和dispatch方法绑定到组件的props上,使得在组件中可以直接调用。以一个login.js Model为例,展示了如何在组件中通过dispatch触发action,并在reducer中更新state。同时,通过mapStateToProps函数,将Model的system数据映射到组件props,方便在DOM中直接使用。

前言: 这是我在学习的时候遇到了这块的内容, 有些可能理解不到位, 还请指出


dva 提供了 connect 方法。如果你熟悉 redux,这个 connect 就是 react-redux 的 connect 。

Connect传递Model中的数据给router

比如model中定义的login.js 定义了state数据,那么在router组件中怎么获取到这个数据呢?

通过connect可以传递过来,然后通过this.props就可以访问了,同样也会将dispatch(可以发送请求到model去),history方法传递过来,这样就可以通过组件传递moel保存的值了

来看看两个模块把

1. index.jsx

import { connect } from 'umi';

const Welcome= (props) => {
    props.dispatch({
        type: 'namespace/functionName'
    })
}

const namespace = 'systembb';
const mapStates = (state) => {
    const systemList = state[namespace].system;
    return {
      systemList
    }
}
export default connect(mapStates)(Welcome);

// 然后就可以在dom中使用 this.props.systemList了

1. models

/***
namespace 表示在全局 state 上的 key
state 是初始值,在这里是空数组
reducers 等同于 redux 里的 reducer,接收 action,同步更新 state

call 用来网络请求, put 然后yield put() 分发给 reducers 中
*/
export default {
  namespace: 'systembb',
  state: {
    system: [
      {
        name: 'this model date'
      }
    ]
  },
  effects: {
    // {paylaod, callback}, {put, call}
    *getdata({payload, _}, { call, put }) {
      yield put({
        type: 'setdata',
        payload: payload
      })
    }
  },
    
  reducers: {
    setdata(state, {payload}) {
      console.log(state)
      return {
        ...state,
        payload
      }
    }
  }
}

Ant Design Pro 中,组件间传值是常见需求,可以通过多种方式实现。以下是详细的传值方法及示例: --- ### **1. 父组件 → 子组件(Props)** 直接通过 `props` 传递数据或函数。 #### 示例 ```tsx // 父组件 import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [count, setCount] = useState(0); return ( <ChildComponent value={count} onIncrement={() => setCount(count + 1)} /> ); }; // 子组件 (ChildComponent.tsx) import React from 'react'; interface Props { value: number; onIncrement: () => void; } const ChildComponent: React.FC<Props> = ({ value, onIncrement }) => ( <div> <p>Count: {value}</p> <button onClick={onIncrement}>Increment</button> </div> ); ``` --- ### **2. 子组件 → 父组件(回调函数)** 通过父组件传递的回调函数,子组件触发父组件状态更新。 #### 示例 ```tsx // 父组件 const ParentComponent = () => { const [message, setMessage] = useState(''); const handleChildSubmit = (text: string) => { setMessage(text); }; return ( <div> <ChildComponent onSubmit={handleChildSubmit} /> <p>子组件传来的值: {message}</p> </div> ); }; // 子组件 interface Props { onSubmit: (text: string) => void; } const ChildComponent: React.FC<Props> = ({ onSubmit }) => { const [inputValue, setInputValue] = useState(''); return ( <div> <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <button onClick={() => onSubmit(inputValue)}>提交</button> </div> ); }; ``` --- ### **3. 兄弟组件间传值(状态提升)** 将共享状态提升到共同的父组件,通过 Props 传递给子组件。 #### 示例 ```tsx // 父组件 const ParentComponent = () => { const [sharedData, setSharedData] = useState(''); return ( <div> <SiblingA onUpdate={setSharedData} /> <SiblingB data={sharedData} /> </div> ); }; // 兄弟组件A (修改数据) const SiblingA = ({ onUpdate }: { onUpdate: (data: string) => void }) => ( <button onClick={() => onUpdate("来自兄弟A的数据")}>更新数据</button> ); // 兄弟组件B (显示数据) const SiblingB = ({ data }: { data: string }) => ( <p>接收到的数据: {data}</p> ); ``` --- ### **4. 跨层级组件传值(Context)** 使用 React Context 避免多层 Props 传递。 #### 示例 ```tsx // 创建 Context const MyContext = React.createContext<{ value: string; setValue: (val: string) => void; } | undefined>(undefined); // 父组件 const ParentComponent = () => { const [value, setValue] = useState("初始值"); return ( <MyContext.Provider value={{ value, setValue }}> <DeepChildComponent /> </MyContext.Provider> ); }; // 深层子组件 const DeepChildComponent = () => { const context = useContext(MyContext); if (!context) return null; const { value, setValue } = context; return ( <div> <p>Context值: {value}</p> <button onClick={() => setValue("新值")}>修改Context</button> </div> ); }; ``` --- ### **5. 全局状态管理(Redux/Model)** 在 Ant Design Pro 中,推荐使用 **Umi + Dva**(或 **Redux Toolkit**)管理全局状态。 #### 示例(Dva Model) ```ts // src/models/example.ts export default { namespace: 'example', state: { value: '', }, reducers: { updateValue(state, action) { return { ...state, value: action.payload }; }, }, }; // 组件A (发送数据) import { connect, Dispatch } from 'umi'; const ComponentA = ({ dispatch }: { dispatch: Dispatch }) => ( <button onClick={() => dispatch({ type: 'example/updateValue', payload: 'Hello' })}> 发送数据 </button> ); // 组件B (接收数据) const ComponentB = ({ value }: { value: string }) => ( <p>全局状态值: {value}</p> ); export default connect(({ example }: { example: { value: string } }) => ({ value: example.value, }))(ComponentB); ``` --- ### **6. 路由参数传值** 通过 `umi` 的 `history` 或 `useParams` 传递参数。 #### 示例 ```tsx // 跳转时传参 import { history } from 'umi'; history.push('/target-path?id=123'); // 或 history.push({ pathname: '/target-path', query: { id: '123' } }); // 目标页面获取参数 import { useLocation } from 'umi'; const TargetPage = () => { const location = useLocation(); const query = new URLSearchParams(location.search); const id = query.get('id'); // "123" return <div>ID: {id}</div>; }; ``` --- ### **7. 事件总线(Event Emitter)** 适用于非父子组件的临时通信(需谨慎使用,避免滥用)。 #### 示例 ```ts // event.ts import { EventEmitter } from 'events'; export const eventBus = new EventEmitter(); // 组件A (发送事件) eventBus.emit('message', { text: 'Hello' }); // 组件B (监听事件) useEffect(() => { const handler = (data: { text: string }) => console.log(data.text); eventBus.on('message', handler); return () => eventBus.off('message', handler); }, []); ``` --- ### **总结** | 场景 | 推荐方式 | |--------------------|--------------------------| | 父子组件传值 | Props / 回调函数 | | 兄弟组件传值 | 状态提升 | | 跨层级组件 | Context | | 全局状态共享 | Redux / Dva Model | | 路由参数传递 | `umi` 的 `history` | | 临时跨组件通信 | 事件总线(慎用) | 根据具体场景选择合适的方式,Ant Design Pro 中优先使用 **Dva Model** 或 **Context** 管理复杂状态。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值