react-redux 之 provider 与 connect 方法

react-redux

众所周知,Redux 是React 全家桶中重要的一员,它试图为 React 提供状态管理机制;个人理解,与Vue中的状态管理Vue-X相似。在使用react开发时,如果要将 Redux 和 React 结合起来使用,往往会选择一个额外的工具,即react-redux 。

react-redux 提供了两个重要的对象,provider 和 connect,前者使 React 组件可被连接(connectable),后者把 React 组件和 Redux 的 store 真正连接起来。

provider

Provider:提供器,在该组件里边的所有组件都可以使用 store,使 React 组件可被连接(connectable)

import { Provider } from 'react-redux'
import store from './store'
const App = (
    <Provider store={store}>
        <Home />
    </Provider>
)

connect

connect:连接器,获取store数据,根据官方文档解释:Connects a React component to a Redux store.It does not modify the component class passed to it. Instead, it returns a new, connected component class, for you to use.

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

connect方法接收四个参数,分别是 mapStateToProps,mapDispatchToProps,mergeProps和options。

1、mapStateToProps(state, ownProps)

mapStateToProps函数允许我们将 store 中的数据作为 props 绑定到组件上。

const mapStateToProps = (state, ownProps) => {
  return {
    count: state.count
  }
}
2、mapDispatchToProps(dispatch, ownProps)

mapDispatchToProps函数将 action 作为 props 绑定到组件上。

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    increase: (...args) => dispatch(actions.increase(...args)),
    decrease: (...args) => dispatch(actions.decrease(...args))
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值