Dva 學習筆記:module解決異步問題(一)

1、聲明reducers;

    reducers:{
        updateProductList(state,action){  
            var currentState=deepClone(state);
            currentState.productList.push(action.payload);
            //console.log(action.payload);
            // return state;
            return currentState;
        }
     }

     updateProductList是定義的函數名稱;

2、直接使用dispatch對象:將dispatch傳給Product;

 <Product title="農副產品" dispatch={ this.props.dispatch }/>

      直接在另一個頁面使用;

 this.props.dispatch({
       type:'product/updateProductList',
       payload:newProductList 
 })

3、 通過dispatch觸發reduce函數;

 type:'product/updateProductList',// 命名空間/函數名=======觸發的方式

       newProductList是一個參數,通過payload的方式傳給action;

 payload:newProductList // newProductList 參數

      然後action就能讀到payload;

reducers:{
        updateProductList(state,action){  
            console.log(action.payload);
            return state;
        }
}

     PS:state不能被改變,否則會引起視圖的不更新,解決方案:【深拷貝】

      深拷貝:創建一個新的對象或者數組,將原對象的各類屬性的‘值’(數組的所有元素)拷貝過來,是【值】而不是引用;

function deepClone(arr) {
    var obj = JSON.stringify(arr);
    var deepObj = JSON.parse(obj);
    return deepObj;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章