redux+react-redux realizes shopping process

redux+react-redux realizes shopping process

In the development process of e-commerce projects, the order and purchase process of goods will be involved. The approximate process is as follows:

  1. The menu shopping cart displays the quantity of goods in real time
  2. Add to shopping cart on product page
  3. Enter the shopping cart page to display the added products

Step 3 above involves three components: a menu component, product assembly, cart assembly, that is to say the data we need data exchange between these three components, as is the use react development of the project, so the introduction of the project reduxrealization For data sharing between multiple components, since reactand reduxare two independent products, there is no direct connection between them, so it is necessary to react-reduxassociate the reactcomponents with the reduxdata.

reduxNeedless to say, it is a state management tool that can help us achieve updates in data management. react-reduxUse Contextof higher-order components to achieve the data sharing issues with the component automatically refreshed.

Everything is there, only the code

One, share redux data

  1. First use redux to create data
    // reducer/index.js
    const initState = {
        cartlist:[]
    }
    function reducer(state=initState,action){
        switch(action.type){
            // 添加商品
            case 'ADD_TO_CART':
                // 返回一个新的State,这个state会自动覆盖store中的旧数据
                return {
                    cartlist: [action.goods, ...state.cartlist]
                }
            // 删除商品
            case 'REMOVE_FROM_CART':
                return {
                    cartlist: state.cartlist.filter(item => item.goods_id != action.goods_id)
                }
            // 修改数量
            case 'CHANGE_QTY':
                return {
                    cartlist: state.cartlist.map(item => {
                        if (item.goods_id === action.goods_id) {
                            item.goods_qty = action.goods_qty
                        }
                        return item;
                    })
                }
            // 清空商品
            case 'CLEAR_CART':
                return {
                    cartlist: []
                }
            default:
                return state;
                
        }
    }
    export default reducer;
    // store/index.js
    import {createStore} from 'redux';
    import reducer from './reducer'
    const store = createStore(reducer);
    export default store;
  1. Use react-redux to share data
    import React from 'react'
    import ReactDOM from 'react-dom'
    import {Provider} from 'react-redux'
    import store from './store'
​
    ReactDOM.render(
        <Provider store={store}>
            <App/>
        </Provider>,
        document.getElementById('app')
    )

Two, the react component receives data

  1. The menu component receives the number of items in the shopping cart
    const mapStateToProps = (state)=>{
        return {
            cartCount:state.cartlist.length
        }
    }
    @connect(mapStateToProps)
    class Menu extends React.Component {
        //...此处省略部分代码
    }
  1. The product page receives the shopping cart product list and the method to add to the shopping cart
    import {connect} from 'react-redux';
​
    @connect((state)=>({
        cartlist:state.cart.cartlist
    }),dispatch=>({
        add2cart(goods){
            dispatch({
                type:'ADD_TO_CART',
                goods
            })
        },
        changeQty(goods_id,goods_qty){
            dispatch({
                type:'CHANGE_QTY',
                goods_id,
                goods_qty
            })
        }
    }))
    class Goods extends Component{
        // ...此处省略一万行代码
    }
  1. The shopping cart page displays products and implements operations such as deleting, emptying the shopping cart, and modifying the quantity of products
    @connect(({cart:{cartlist}})=>({
        cartlist,
        totalPrice:cartlist.reduce((prev,item,idx,arr)=>prev+item.goods_price*item.goods_qty,0)
    }),(dispatch)=>{
        return {
            removeCart(goods_id){
                dispatch({
                    type:'REMOVE_FROM_CART',
                    goods_id
                })
            },
            clearCart(){
                dispatch({
                    type:'CLEAR_CART',
                })
            },
            changeQty(goods_id,goods_qty){
                dispatch({
                    type:'CHANGE_QTY',
                    goods_id,
                    goods_qty
                })
            }
        }
​
    })
    class Cart extends Component{
        // ...此处继续省略一万行代码
    }

Effect picture

The menu effects are as follows:

The product page effects are as follows:

 

Conclusion

redux + react-redux implements the complete process of adding a product to the shopping cart. The careful friends found that redux and react-redux each implement different functions:

  • reduxDefine the initial data state, and provide a statemethod of modification through the reducer
  • react-reduxUse Context to share data in redux ( <Provider/>), and use higher-order components ( connect()) to pass data as props to components

The principle is actually very simple. The <Provider/>use of components Contextrealizes data sharing between components. No matter how deep the component level is, the data on redux can be directly obtained, while connect()high-level components pass redux data to React components through props. The advantage of props is that when the redux data is modified (that is, the props are modified) the component will automatically refresh.

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/108580517