dva学习--connect数据(model和router)

Connect 传递model中的数据给组件router

    前面的model的demo中定义的example.js中定义了state数据,那么在route的路由组件中怎么获取到这个数据呢?

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

方式一:

import React from "react";
import {Component} from 'react';
import { connect } from "dva"; //从dva中导入connect

class Counter extends Component {
    constructor(props){
        super(props)
    }  
    render (){
        return (
            <div>
                 <p> this.props.example.initText</p> //如这里就获取到了上面定义的initText数据了
            </div>
        )
    }
}
const mapStateToProps = (state) =>{
    return {
        example:state.example, //这里的example表示后面用this.props.example获取state(根节点)中exmpale命名空间(model的example.js中的state所有数据)的数据
    }
}
export default connect (mapStateToProps)(Counter) //通过这种方式来把model层的数据传递到当前组件了
 

当然是用connect也不仅仅是只有这一种方式:

 方式二:

      export default connect ({example})(Counter) //通过这种方式来把model层的数据传递到当前组件了

import React from "react";
import {Component} from 'react';
import { connect } from "dva"; //从dva中导入connect

class Counter extends Component {
    constructor(props){
        super(props)
    }  
    render (){
        return (
            <div>
                 <p> this.props.example.initText</p> //如这里就获取到了上面定义的initText数据了
            </div>
        )
    }
}

export default connect ({example})(Counter) //通过这种方式来把model层的数据传递到当前组件了,默认这面的也是example属性,通过this.props.example可以获取到model(example.js)中state的数据了
 

方式三:采用ES6注解的形式传递值,都是一样的

import React from "react";
import {Component} from 'react';
import { connect } from "dva"; //从dva中导入connect

@connect({example})
class Counter extends Component {
    constructor(props){
        super(props)
    }  
    render (){
        return (
            <div>
                 <p> this.props.example.initText</p> //如这里就获取到了上面定义的initText数据了
            </div>
        )
    }
}

    

  • 10
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值