react-redux源码分析

1.Redux设计理念

Redux是将整个应用状态存储到一个地方上称为store,里面保存着一个状态树store tree,组件可以派发(dispatch)行为(action)给store,而不是直接通知其他组件,组件内部通过订阅store中的状态state来刷新自己的视图。
在这里插入图片描述

2. Redux三大原则

1 唯一数据源
整个应用的state都被存储到一个状态树里面,并且这个状态树,只存在于唯一的store中

2 保持只读状态
state是只读的,唯一改变state的方法就是触发action,action是一个用于描述以发生时间的普通对象

3 数据改变只能通过纯函数来执行
使用纯函数来执行修改,为了描述action如何改变state的,你需要编写reducers

connect

// (mapStateToProps = state => state, mapDispatchToProps = {}) => (WrapComponent) => {}: 就是个高阶组件,装饰WrapComponent组件
export const connect = (mapStateToProps = state => state, mapDispatchToProps = {}) => (WrapComponent) => {
  return class ConnectComponent extends React.Component {
    // 老式的上下文声明,constructor里面就可以拿到context
    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
      //按照mapStateToProps声明的规则进行映射,拿到所需的状态对象
      const stateProps = mapStateToProps(store.getState())
      const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch)
      this.setState({
        props: {
          ...this.state.props,
          ...stateProps,
          ...dispatchProps
        }
      })
    }

    render() {
      <WrapComponent {...this.state.props} />
    }
  }
}
function bindActionCreators(creators,dispatch){
  return Object.keys(creators).reduce((ret,item)=>{
    ret[item] = bindActionCreator(creators[item],dispatch)
    return ret
  })
}

bindActionCreators = (creators,dispatch) => {
  return Object.keys(creators).reduce((ret,item)=>{
    ret[item] = bindActionCreator(creators[item],dispatch)
    return ret
  })
}

Provider

export class Provider extends React.Component{
// 老式上下文传递方式,childContextTypes和getChildContext,可以将{store:this.store}传递到子代去
  static childContextTypes = {
    store: PropTypes.object
  }

  getChildContext(){
    return {store:this.store}
  }

  constructor(props, context){
    super(props, context)
    this.store = context.store
  }

  render() {
    return this.props.children
  }
}

thunk

const thunk = ({dispatch,getState})=>next=>action=>{
if (typeof action=='function') {
return action(dispatch,getState)
}
return next(action)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值