Redux和React-Redux的实现(二):Provider组件和connect的实现
接着上一篇讲,上一篇我们实现了自己的Redux和介绍了React的context以及Provider的原理。
1. Provider组件的实现
Provider组件主要有以下下两个作用
- 在整个应用上包一层,使整个应用成为Provider的子组件
- 接收Redux的store作为props,通过context对象传递给子组件,所有的子组件都可以取得store
首先我们要知道,Provider组件的任务是将stroe传递给子组件,它只是一个传递数据的组件,只需要将子组件展示出来就好。
import React from 'react'
import PropTypes from 'prop-types'
export class Provider extends React.Component{
static childContextTypes = {
store: PropTypes.object
}
getChildContext(){
return {store:this.store}
}
constructor(props, context){
super(props, context)
this.store = props.store
}
render(){
return this.props.children
}
}
2. connect方法
connect的作用就是将React和Redux中的store连接起来
首先要明确它的任务:
- 接收一个组件,将Redux中的store通过props传递给组件
- 将Redux中的action也通过props传递给组件
- 返回一个新的组件,这个组件可以通过this.props访问到store中的属性,也可能是触发action
- 当store中的数据发生变化的时候,通知新的组件
根据它的任务就能知道,它是一个高阶函数
connect方法定义
官方给出connect的定义:
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
非常好理解了,在React-Redux中,我们常用的就是前两个参数。
mapStateToProps
这个函数帮助我们将store中的数据作为props传递给组件,也就是实现了connect方法的第一个任务
mapStateToProps(state, ownProps) : stateProps
- mapStateToProps的第一个参数就是Redux的store
- 第二个参数就是自己的props,也可已将自己的props和store merge到一起传递给组件
我们经常这么使用mapStateToProps
state=>({ num: state})
或者这样只获取我们当前需要的属性
const mapStateToProps = (state) => {
return {
num: state.num
}
}
mapDispatchToProps
这个函数的会将action以props的形式传递给组件,组件可用this.props触发相应action,也就是完成了上面的第二个任务。
mapDispatchToProps(dispatch, ownProps): dispatchProps
这个函数返回的是装有action的对象,通常我们直接给它赋值成一个对象,再把我们的action放进去。
import { add, remove, addAsync } from './index.redux'
mapDispatchToProps = { add, remove, addAsync }
从这里看好像是完成了我们的任务,但是注意:在我们的组件可以通过this.props触发相应的action,但是还没有dispatch,所以只返回了一个type,所以上面的代码并不是正确的,只是便于大家理解。
我们还需要dispatch一下action,下面才是正确的代码:
const mapDispatchToProps = (dispatch, ownProps) => {
return {
add: (...args) => dispatch(actions.add(...args)),
remove: (...args) => dispatch(actions.remove(...args)),
addAsync: (...args) => dispatch(actions.addAsync(...args))
}
}
有人会问,我用React-Redux的connect时,这个参数直接穿的是action对象呀,怎么回事?
这是因为在connect内部使用了Redux提供的bindActionCreators方法,在connect内部将所有的action都dispatch了。我们实现的时候,也需要实现这个bindActionCreators方法。
mergeProps
mergeProps顾名思义,就是将stateProps、dispatchProps、ownProps合并起来。
如果不指定mergeProps,默认用Object.assign
function mergeProps(stateProps, dispatchProps, ownProps) {
return Object.assign({}, ownProps, {
num: stateProps.num,
add: () => dispatchProps.add(),
remove: () => dispatchProps.remove(),
addAsync: () => dispatchProps.addAsync(),
})
}
options
规定connector的行为,通常我们使用默认值。
connect方法的使用
我们常见的写法,也就是ES7的decorator装饰器,也就是装饰者模式,这种写法比较简便:
@connect(
state=>({ num: state}),
{ add, remove, addAsync }
)
class App extends React.Component{
render(){
return (
<div>
<h2>现在有物品{this.props.num}件</h2>
<button onClick={this.props.add}>add</button>
<button onClick={this.props.remove}>remove</button>
<button onClick={this.props.addAsync}>addAsync</button>
</div>
)
}
}
export default App;
或者是更容易理解的高阶函数的写法:
class App extends React.Component{
render(){
return (
<div>
<h2>现在有物品{this.props.num}件</h2>
<button onClick={this.props.add}>add</button>
<button onClick={this.props.remove}>remove</button>
<button onClick={this.props.addAsync}>addAsync</button>
</div>
)
}
}
App = connect(
state => ({num: state),
{ add, remove, addAsync }
)(App)
第二中写法我们可以更好的理解connect函数如何工作:connect接受了它的四个参数,然后返回了一个高阶组件,高阶组件需要接收一个组件作为参数,在高阶组件中通过处理被传入的组件,其中用到了connect的四个参数,最后将处理后的组件返回出去。
3. mapStateToProps的实现
connect方法返回了一个函数,函数里返回了一个组件,有两次返回,这里我们用两层箭头函数:
export const connect = (mapStateToProps = (state) => state, mapDispatchToProps={}) => (WrapComponent) => {
return class ConnectComponent extends React.Component{
}
}
它等价于这种写法:
export function connect (mapStateToProps = (state) => state, mapDispatchToProps={}) {
return function (WrapComponent) {
return class ConnectComponent extends React.Component{
}
}
}
双层箭头函数更加简洁,也算是编写高阶函数的一个技巧吧。
mapStateToProps的任务已经明确,先接收一个,获取Redux中的store,将stroe通过props传递给组件,代码如下:
import React from 'react'
import PropTypes from 'prop-types'
export const connect = (mapStateToProps = (state) => state, mapDispatchToProps={}) => (WrapComponent) => {
return class ConnectComponent extends React.Component{
static contextTypes = {
store: PropTypes.object
}
constructor (props, context) {
super(props, context)
this.state = {
props: {}
}
}
componentDidMount () {
const {store} = this.context
this.update()
store.subscribe(()=>this.update())
}
update () {
const { store } = this.context
const stateProps = mapStateToProps(store.getState())
this.setState({
props: {
...this.state.props,
...stateProps
}
})
}
render () {
return <WrapComponent {...this.props}/>
}
}
}
很明确,我们先用context获取了Provider组件传递过来的store然后将this.props与store中的属性merge成一个新的this.props传递给组件,组件mount的时候用store.subscribe监听了store内数据的变化,从而实时通知组件,完成了connect的第四个任务。
4. mapDispatchToProps的实现
介绍mapDispatchToProps的是有也说了,传递进来的action不能直接使用,需要dispatch一下,Redux提供了一个bindActionCreators方法,同样我们也在自己的Reudx中实现这个方法。
接着上面的代码来写
import React from 'react'
import PropTypes from 'prop-types'
import {bindActionCreators} from './myRedux'
export const connect = (mapStateToProps=state=>state,mapDispatchToProps={})=>(WrapComponent)=>{
return class ConnectComponent extends React.Component{
static contextTypes = {
store:PropTypes.object
}
constructor(props, context){
super(props, context)
this.state = {
props:{}
}
}
componentDidMount(){
const {store} = this.context
store.subscribe(()=>this.update())
this.update()
}
update(){
const {store} = this.context
const stateProps = mapStateToProps(store.getState())
const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch)
this.setState({
props:{
...this.state.props,
...stateProps,
...dispatchProps
}
})
}
render(){
return <WrapComponent {...this.state.props}></WrapComponent>
}
}
}
这个很简单,主要的就是bindActionCreators方法,写在我们自己的Redux中
function bindActionCreator(creator, dispatch){
return (...args) => dispatch(creator(...args))
}
export function bindActionCreators(creators, dispatch){
return Object.keys(creators).reduce((ret,item)=>{
ret[item] = bindActionCreator(creators[item],dispatch)
return ret
},{})
}
也不是很难理解,遍历对象中的所有action,每个action都dispatch一下,返回每一个dispatch之后的action。
比如之前的add方法为:add(args),现在的add方法是:store.dispatch(add(args))
现在我们的Provider组件和connect高阶函数已经实现,下一篇我们实现Redux的中间件。
Redux和React-Redux的实现(二):Provider组件和connect的实现的更多相关文章
- react.js 从零开始(二)组件的生命周期
什么是生命周期? 组件本质上是一个状态机,输入确定,输出一定确定. 当状态改变的时候 会触发不同的钩子函数,可以让开发者做出响应.. 一个组件的生命周期可以概括为 初始化:状态下 可以自定义的函数 g ...
- react + redux 完整的项目,同时写一下个人感悟
先附上项目源码地址和原文章地址:https://github.com/bailicangd... 做React需要会什么? react的功能其实很单一,主要负责渲染的功能,现有的框架,比如angula ...
- React + Redux 入坑指南
Redux 原理 1. 单一数据源 all states ==>Store 随着组件的复杂度上升(包括交互逻辑和业务逻辑),数据来源逐渐混乱,导致组件内部数据调用十分复杂,会产生数据冗余或者混用 ...
- react redux 二次开发流程
在一个大项目中如何引入redux及其相关技术栈(react-redux redux-thunk redux-immutable ),已经成为react前端工程师不可或缺的技能,下面通过实现一个简单的t ...
- react+redux教程(二)redux的单一状态树完全替代了react的状态机?
上篇react+redux教程,我们讲解了官方计数器的代码实现,react+redux教程(一).我们发现我们没有用到react组件本身的state,而是通过props来导入数据和操作的. 我们知道r ...
- webpack+react+redux+es6开发模式
一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...
- webpack+react+redux+es6
一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...
- 详解react/redux的服务端渲染:页面性能与SEO
亟待解决的疑问 为什么服务端渲染首屏渲染快?(对比客户端首屏渲染) react客户端渲染的一大痛点就是首屏渲染速度慢问题,因为react是一个单页面应用,大多数的资源需要在首次渲染前就加载 ...
- 【redux】详解react/redux的服务端渲染:页面性能与SEO
亟待解决的疑问 为什么服务端渲染首屏渲染快?(对比客户端首屏渲染) react客户端渲染的一大痛点就是首屏渲染速度慢问题,因为react是一个单页面应用,大多数的资源需要在首次渲染前就加载 ...
随机推荐
- [NOIp2016]蚯蚓 (队列)
#\(\color{red}{\mathcal{Description}}\) LInk 这道题是个\(zz\)题 #\(\color{red}{\mathcal{Solution}}\) 我们考虑如 ...
- boost::bind 学习
最近学习了太多与MacOS与Iphone相关的东西,因为不会有太多人有兴趣,学习的平台又是MacOS,不太喜欢MacOS下的输入法,所以写下来的东西少了很多. 等我学习的东西慢慢的与平台无关的时 ...
- ios学习路线—Objective-C(装箱和拆箱)
概述 从前面的博文我们也可以看到,数组和字典中只能存储对象类型,其他基本类型和结构体是没有办法放到数组和字典中的,当然你也是无法给它们发送消息的也就是说有些NSObject的方法是无法调用的,这个时候 ...
- jQuery带缩略图轮播效果图片切换带缩略图
以上为效果图 HTML代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /& ...
- day 85 Vue学习之vue-cli脚手架下载安装及配置
1. 先下载node.js,下载地址:https://nodejs.org/en/download/ 找个目录保存,解压下载的文件,然后配置环境变量,将下面的路径配置到环境变量中. 由于 Node ...
- Linux-2.6_LCD驱动学习
内核自带的驱动LCD,drivers/video/Fbmem.c LCD驱动程序 假设app: open("/dev/fb0", ...) 主设备号: 29, 次设备号: 0--- ...
- [shell]关闭超时的进程
应同事要求,写了个shell, 主要功能为查找超时的进程,并关闭! 调用方式: shell_sheep : 为进程名 30 : 为30分钟 从打印的日志能看出会多两个PID,不要惊慌,由于你执行时会 ...
- bzoj 4689: Find the Outlier
数据不大,枚举哪个式子错了,对剩下的d+2个式子随意选d+1个高斯消元,然后代入剩下的式子检查是否正确,正确就是那一个式子错了 #include<bits/stdc++.h> #defin ...
- [Luogu4182][USACO18JAN]Lifeguards P[单调队列]
题意 给定 \(n\) 个区间,必须去掉其中的 \(K\) 个,询问能够保留的区间并的最大值. \(n \leq 10^5\ ,K \leq 100\) . 分析 定义状态 \(f_{i,j}\) 表 ...
- Java虚拟机笔记(三):垃圾收集算法
一.标记-清除(Mark-Sweep)算法 标记清除算法是最基础的收集算法,其他收集算法都是基于这种思想. 标记清除算法分为“标记”和“清除”两个阶段:首先标记出需要回收的对象,标记完成之后统一清除对 ...