react中使用redux

现在我们如果在react中使用redux,有什么不足之处:

1)不管是哪一个组件中使用仓库,都需要引入,不方便
2)在组件中派发一个action时,需要引入store,还需要引入action

理想情况下:

1)把store在根组件中提供 所有的子组件都可以使用之
2)如果把仓库中的状态映射成组件的属性 this.props.xxx
3)如果把派发动作的操作映射成组件的方法

下面介绍一下react-redux:

介绍:这是一个独立的模块,这个模块,可以让我们非常方便的在react中使用redux
安装:npm i react-redux

在react-redux中提供了两个东西:

Provider组件:
可以给所有的组件提供仓库。
connect方法:
可以把方法和状态映射到组件的属性上。

react-redux的使用

1、Provider是一个组件
在这里插入图片描述

如何插入一段漂亮的代码片

import React, { Component } from 'react'
import { connect } from "react-redux"  //是一个方法
import Add from '../components/Add'
import AsyncAdd from '../components/AsyncAdd'
import Show from '../components/Show'
import Sub from '../components/Sub'  //把action creators导进来
import { increment, decrement, incrementAsync } from "../store/action creators/counter"
class Counter extends Component {
    render() {
        return (
            <div>   //传给子组件
                <Show counter={ this.props.counter }></Show>
                <p>
                    <Add increment={ this.props.increment }></Add>
                    <Sub decrement={ this.props.decrement }></Sub>
                    <AsyncAdd incrementAsync={ this.props.incrementAsync }></AsyncAdd>
                </p>
            </div>
        )
    }
}
//把映射好的组件导出去
export default connect(state=>( {counter:state.counter} ), {increment, decrement, incrementAsync})(Counter)
// 把仓库中的状态映射成组件的属性     就可以往下传递了
// function mapStateToProps(state) {  // state代表仓库中的状态
//     return{
//         counter:state.counter
//     }
// }    =>    state=>( {counter:state.counter}
// function mapDispatchToProps(params) {
//     // ....
// }
// 把一个UI组件 转化成 一个智能组件(把仓库中的状态和方法映射到组件中)
// export default connect(mapStateToProps,null)(Counter)
// 第2个参数和可以直接写action creator
// 把仓库中的状态映射成组件的属性,把仓库中的action也映射成组件的属性

先映射到Counter组件上,然后传递给子组件,子组件就可以使用了 通过this.props .xxx进行使用

子组件的使用

import React, { Component } from 'react'

export default class Add extends Component {
    render() {
        return (  //直接
            <button onClick={ e=>this.props.increment() }>1</button>
        )
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值