20180911 redux 粗浅使用

作者: Aaron_Alphabet | 来源:发表于2018-09-10 17:30 被阅读3次

    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 的一个脑图

    redux.png

    相关文章

      网友评论

        本文标题:20180911 redux 粗浅使用

        本文链接:https://www.haomeiwen.com/subject/jqtegftx.html