redux 和 react-redux 使用筆記

redux就是一個數據管理工具

  • action ---數據層,公共約定
  • reducer --根據dispatch發布更新處理action數據,建議返回新state。
  • store ---1 dispatch發布事件,2getState()獲取stage,3subscribe監聽觸發
    事件 參考例子 git>https://github.com/mazhenxiao/ProcessTimeLine.git

redux 簡單實例

import { createStore } from 'redux';
//action 實例,就是一個數據結構約定,type為該數據識別碼
let db = {
 "type":"storeIndex",
 "data":{
     "list":[],
     "show":true
 }
}
//reducer實例,處理觸發器觸發后如何返回數據。
 let reducer=(state=db,action)=>{
   let {data,type} = action;
    if(type=="storeIndex"){
        return Object.assign({},state,action) //建議返回新對象不直接改初始對象
    }
    return state;
}
//store實例,綁定reduce
let store = createStore(reducer);
//store監聽實例,類似dom層addEventlistener
     store.subscribe(() => 
             //store.getState(),返回reducer處理過的數據
             console.log(store.getState()) 
      );
//store.dispatch 發布實例
      store.dispatch({
          "type":"storeIndex",
          "data":{
               "list":[1,2,3,4,5,6],
               "show":true
           }
      })

export default store

react-redux,我不茍同但是開發只能隨大溜,公共約定。

  • <Provider store={store}> 組件
  • connect 綁定組件

react-redux 實例

1、Provider 組件綁定

import React,{Component} from "react";
import {Provider} from "react-redux";
import { BrowserRouter as Router,Route} from 'react-router-dom';
import store from "@js/redux";
import ViewIndex from "@view/index";

class Prouter extends Component{
    render(){
        return <Provider store={store}> //store 參照redux生成
                     <Router>
                         <Route exact path="/" component={ViewIndex} />
                    </Router> 
               </Provider>
    }
}
export default Prouter

2、connect 綁定組件,注入redux的action到組件的props,也是關鍵步驟,并且蹩腳。

以高階函數綁定當前組件

  • mapStateToProps: 相當于過濾filter,返回當前項目所需action
  • mapDispatchToProps: 在props里注入一個函數,并給函數注入參數dispatch,用來發布更新action,此處實例我自定義了個onLoad在componentDidMount中執行,并將dispatch 提取出來在當前類使用。
import React, { Component } from "react";
import controllerIndex from "./controller-index";
import actionIndex from "./action-index";
import {connect} from "react-redux";

class VIewIndex extends Component{
    constructor(props, context){
        super(props, context);
        this.dispatch=null;
    }
 componentDidMount(){
        this.props.onLoad(dispatch=>this.dispatch=dispatch);
    }
 Event_Click_Getstate(event){
         this.dispatch({
            type:"storeIndex",
            data:{
               list:[{
                   startTime:"1234123"
               }]
            }
         }) 
     }
    render(){
        let {storeIndex} = this.props
        return <article onClick={this.Event_Click_Getstate.bind(this)}>
              {
                   storeIndex.data.list.map((da,ind)=>{
                    return <p key={ind}>{da.startTime}</p>
                  })  
              }
        </article>
    }
}
//過濾當前所需action
const mapStateToProps=(state)=>{ 
    return {storeIndex:state.storeIndex}
}
// 在props里注入自定義函數,為了返回dispatch用來發布action
const mapDispatchToProps=(dispatch)=>{
   return {
        onLoad(callback){ callback(dispatch) }
   }
}

//此處為關鍵所在
export default connect(mapStateToProps,mapDispatchToProps)(VIewIndex);

源碼解析

一直吐槽為神馬不直接注入到組件,還得去高階嵌套,于是翻閱react-redux到Provider,發現他只是如實中轉了store

 class Provider extends Component {
        getChildContext() {
          return { [storeKey]: this[storeKey], [subscriptionKey]: null }
        }

        constructor(props, context) {
          super(props, context)
          this[storeKey] = props.store;
        }

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

既然已經開始處理子元素了,為什么不直接向下逐層添加props,于是我就嘗試去添加,發現報錯,于是翻開react源碼找原因,發現竟然凍結了子元素的props屬性Object.freeze(childArray); 所以無法直接逐層注入,否則使用react.Children.map 方法可以逐一或遞歸注入到props里

 // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.
  var childrenLength = arguments.length - 2;
  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);
    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }
    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }
    props.children = childArray;
  }

connect 事件發布mapDispatchToProps,使用了recux的bindActionCreators 方法綁定函數并傳入dispatch作為參數

export function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
  return (mapDispatchToProps && typeof mapDispatchToProps === 'object')
    ? wrapMapToPropsConstant(dispatch => bindActionCreators(mapDispatchToProps, dispatch))
    : undefined
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容