react-redux源码解析

react-redux是为react而生的,是为了在react项目中能够更方便的使用redux,所以有了react-redux这个库。
在这里插入图片描述
context.js是跨级通信的对象,通过react.createContext创建

import React from 'react';
const ReduxContext = React.createContext(null);
export default ReduxContext;

Provider.js是一个组件是相当于提供商,提供redux库中store对象。

import React, { Component } from 'react'
import ReduxContext from './context';
export default class Provider extends Component {
  render() {
    return (
      <ReduxContext.Provider value={{store:this.props.store}}>
        {this.props.children}
      </ReduxContext.Provider>
    )
  }
}

connect.js是用来将组件与redux之间进行一个关联,并将每个组件公共的代码提取出来。connect.js通过store对象的getState函数获取公共仓库state对象,订阅store对象通过setState函数实时更新组件本地状态,通过redux的bindActionCreators函数将action进行自动绑定到dispatch上。

import React,{Component} from 'react';
import {bindActionCreators} from '../redux';
import ReactContext from './context.js';

export default function(mapStateToProps,mapDispatchToProps){
  return function(WrappendComponent){
    return class extends Component{
      static contextType=ReactContext;
      constructor(props,context){
        super(props);
        this.state=mapStateToProps(context.store.getState());
      }
      componentDidMount(){
        this.unsubscribe=this.context.store.subscribe(()=>{
          this.setState(mapStateToProps(this.context.store.getState()))
        })
      };
      componentWillUnmount(){
        this.unsubscribe();
      }
      render(){
        let actions={};
        if(typeof mapDispatchToProps==='function'){
          actions=mapDispatchToProps(this.context.store.dispatch);
        }else{
          actions=bindActionCreators(mapDispatchToProps,this.context.store.dispatch);
        }
        return (
          <WrappendComponent {...this.state} {...actions}></WrappendComponent>
        )
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值