为了账号安全,请及时绑定邮箱和手机立即绑定

20180911 redux 粗浅使用

标签:
JavaScript

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://img1.sycdn.imooc.com//5d51778000015ac414040417.jpg

redux.png



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


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消