Dva系列:connect与@connect的使用(一) | 您所在的位置:网站首页 › dva的q怎么用 › Dva系列:connect与@connect的使用(一) |
前言
在刚开始使用Dva的时候,写好models,通过connect进行仓库与组件的链接的时候怎么不是很理解,翻译官方文档也没有明确的解释。 提示:以下是本篇文章正文内容,下面案例可供参考 一、connect的用来干什么connect用来链接组件和状态管理器。你可以通过dispath调用对应仓库中的方法,也可以通过在this.props下找到仓库的数据进行操作。 connect 方法返回的也是一个 React 组件,通常称为容器组件。因为它是原始 UI 组件的容器,即在外面包了一层 State。 connect 方法传入的第一个参数是 mapStateToProps 函数,mapStateToProps 函数会返回一个对象,用于建立 State 到 Props 的映射关系。 我们现在来看看connect组件后,this.props中会出现什么。 可以看到this.props中会多一个region这个属性,这个属性也就是你namespace为region的仓库中的所有内容。 loading:是判断这个数据是否以及加载完成。region:是返回过来的数据。router:是触发请求的时候,页面的路由这里是models目录下的Region.js文件 import {getRegionList} from '../../server/server' export default { namespace: 'region', state: {}, effects: { *getList({payload},{put,call}){ const res = yield call(getRegionList,payload) if(res.status == 200){ yield put({ type:'add', payload:res.data.data || {} }) } } }, reducers: { add(state, action){ return { ...state, data: action.payload } } } }这里是与models在同一文件夹下的index.js目前 import styles from './index.css'; import { connect } from 'dva'; import React from 'react'; import { Cascader } from 'antd'; // [{ // value: 'zhejiang', // label: 'Zhejiang', // children: [ // { // value: 'hangzhou', // label: 'Hangzhou', // children: [ // { // value: 'xihu', // label: 'West Lake', // }, // ], // }, // ], // },] class Region extends React.Component { constructor (props){ super(props) this.state = { data : [], } } componentDidMount(){ const { dispatch } = this.props; dispatch({ type:'region/getList', payload: {} }).then((res) => { this.setState({ data:this.props.region.data }) }) } patch = () => { const { dispatch } = this.props; dispatch({ type:'region/add', payload: {} }) } onChange = (value) => { console.log(value); } render(){ const options = [this.state.data] return ( 惦记我{} { label: 'mc', value: 'id', children: 'children' }} rowkey='id'/>, ); } } export default Region 总结上述是对Dva中使用connect以及@connect的说明,根据自己喜好选择方式即可。 |
CopyRight 2018-2019 实验室设备网 版权所有 |