React redux & React-redux

92 阅读1分钟

1、Redux

npm install --save redux
import { createStore } from 'redux'


// reducer:变更 state 的地方
const reducer = (state = {count: 0}, action) => {
  switch (action.type){
    case 'INCREASE': return {count: state.count + 1};
    case 'DECREASE': return {count: state.count - 1};
    default: return state;
  }
}


// actions:触发动作
const actions = {
  increase: () => ({type: 'INCREASE'}),
  decrease: () => ({type: 'DECREASE'})
}


// 工厂函数,创建 store 对象
const store = createStore(reducer);


// 数据更新,触发订阅的依赖 components
store.subscribe(() =>
  console.log(store.getState())
);


// dispatch:触发数据更新的操作
store.dispatch(actions.increase()) // {count: 1}
store.dispatch(actions.increase()) // {count: 2}
store.dispatch(actions.decrease()) // {count: 1}

2、React-redux

image.png

import React, { Component } from 'react';
import store from '../store';
import actions from '../store/actions/list';
import {connect} from 'react-redux';

class Todos extends Component {
    render(){
        return(
            <div onCLick={()=>this.props.del_todo() }>test</div>
        )
    }
}

// connect:核心逻辑:监听 props、store中state 数据变化更新当前组件
export default connect(
    state => state,
    actions
)(Todos);

3、connect原理简化版

import React,{Component} from 'react';
import {bindActionCreators} from 'redux';
import propTypes from 'prop-types';

export default function(mapStateToProps,mapDispatchToProps){
   return function(WrapedComponent){
      class ProxyComponent extends Component{
          static contextTypes = {
              store:propTypes.object
          }
          constructor(props,context){
            super(props,context);
            this.store = context.store;
            this.state = mapStateToProps(this.store.getState());
          }
          componentWillMount(){
              this.unsubscribe = this.store.subscribe(()=>{
                  this.setState(mapStateToProps(this.store.getState()));
              });
          }
          componentWillUnmount(){
              this.unsubscribe();
          }
          render(){
              let actions= {};
              if(typeof mapDispatchToProps == 'function'){
                actions = mapDispatchToProps(this.store.disaptch);
              }else if(typeof mapDispatchToProps == 'object'){
                actions = bindActionCreators(mapDispatchToProps,this.store.dispatch);
              }
              return <WrapedComponent {...this.state} {...actions}/>
         }
      }
      return ProxyComponent;
   }
}