继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

20180911 redux 粗浅使用

素胚勾勒不出你
关注TA
已关注
手记 176
粉丝 53
获赞 274

redux是一个状态管理器

redux的三个部分:

  • action

  • reducer

     用于生成各种state,
     state就是redux的数据载体,可以是数组,也可以是对象
  • store

     // store由createStore生成
     const store = createStore(store);
    • dispatch

       // dispatch需要派发属性为type的对象,这个对象一般都在action中存着
       store.dispatch({   type:'aciton'
       });
    • subscribe

       // 订阅store的变化
       let sub = store.subscribe(listener); // subscribe 返回的函数用来注销相应的监听器
       sub();
    • getState

       // getState 是一个方法,获取当前的状态
       store.getState(); // 结合上一个api进行使用
       store.subscribe(() => {
         store.getState(); // 监听并获取当前的状态
       })

react-redux

  • Provider (这是一个组件)

    • 组件有一个属性 store 传入的就是 上面生成的store

  • connect (HOC 这是一个高阶组件)

     const ComponentTest = (props) => <ComponentA value={props.value} event={props.event}> const NewComponent = connect( 
                                   mapStateToProps,
                                   mapDispatchToProps
                                  )(ComponentTest)
    • mapStateToProps 这里需要返回一个对象

      const mapStateToProps = (state, ownerProps) => {   // ownerProps 是 NewComponent 上传入的属性
         // reducer上的state
         // 此处的state不是react的state
         // 这块就是将redux的state映射到组件ComponentTest的props上的过程
         return {     value: state.value
         }
      }
    • mapDispatchToProps 这里也需要返回一个对象

      const mapDispatchToProps = (dispatch, ownerProps) => {  // ComponentTest 上的事件event 派发某个action
        // 这块是将redux的派发事件映射到组件ComponentTest 的props上,组件的事件激发了派发事件
        return {    event:() => dispatch({type:'action'})
        }
      }
    • connect()(Component)

      // 当connect中不传任何参数的时候:// Component 这个组件上props传入dispatch,也就是说class ComponentTest extends Component{
        render(){    // 这个组件的props上会有有个dispatch的方法
          const dispatch = this.props.dispatch
        }
      }

redux 中间件,我表示不懂,也不会用

  • applyMiddleware(...[中间件])

redux 的一个脑图

https://img.mukewang.com/5d51778000015ac414040417.jpg

redux.png



作者:Aaron_Alphabet
链接:https://www.jianshu.com/p/55bbcacaf43e


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP