美文网首页
Redux实现简单购物车

Redux实现简单购物车

作者: 未来在奋斗 | 来源:发表于2019-12-22 21:56 被阅读0次

购物车页面

import React,{Component, useState} from 'react'
import store from '../../store'

class Ct extends Component{
    constructor(){
        super()
        this.state ={
            //组件自身的数据 store.getState() 回去仓库中数据的方法 是方法
            name: store.getState().name,
            cards: store.getState().cards
        }
        // store.subscribe()  该方法在仓库数据发生变化时执行
        store.subscribe(()=>{
            this.setState({
                //在仓库数据变化时,更新组件数据
                name:store.getState().name,
                cards:store.getState().cards
            })
        })
      
    }
    render(){
        return(
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>名称</th>
                            <th>价格</th>
                            <th>
                              数量
                            </th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                       {
                           this.state.cards.map(item =>{
                               return(
                                <tr key={item.id}>
                           <td>{item.id}</td>
                               <td>{item.name}</td>
                               <td>{item.price}</td>
                                <td>
                                    <button onClick={
                                        ()=>{this.jian(item)}
                                    } 
                                    style={{width:'40px'}}
                                    >-</button>
                                        {item.num}
                                    <button onClick={
                                        ()=>{this.handleAdd(item)}
                                    }>+</button>    
                                </td> 
                                </tr>
                               )
                           })
                       }
                    </tbody>
                </table>
            </div>
        )
    }
    handleAdd=(item) =>{
        // 提交动作
        store.dispatch({
            // 提交的验证
            type: 'ADD_TODO',
            // 提交的数据
            good:item
        })
    }
    jian=(item)=>{
         // 提交动作
         store.dispatch({
            // 提交的验证
            type: 'JIAN_TODO',
            // 提交的数据
            good:item
        })
    }
}


const Cart = ()=>{
    const [gooods,setGooods] =useState([
        {id:1,name:'手机',price:2000},
        {id:2,name:'笔记本电脑',price:5000},
        {id:3,name:'手表',price:12000},
    ])
    
  function add(item){
        store.dispatch({
            // 提交的验证
            type: 'ADD_TODO',
            // 提交的数据
            good:item
        })
    }
    return(
        <div>
            <h2>商品展示页</h2>
            <ul>
                {
                    gooods.map(item=>{
                        return (
                            <li key={item.id}>
                                {item.name}
                                <button onClick={()=>{
                                    add(item)
                                }}>+</button>
                            </li>
                        )
                    })
                }
            </ul>
            <hr/>
            <Ct></Ct>
        </div>
    )
 
}

export default Cart

Redux页面

import {createStore} from 'redux'
// 返回新的数据不直接修改
const reducer = (state,action)=>{
//  验证 action.type 提交动作的验证属性type
    if(action.type === 'ADD_TODO'){
        // 做一个拷贝 因为不能直接修改所以需要拷贝用新的数据去退换旧的数据
        //  拷贝要做深拷贝不然新旧数据都会变
        //  1. 深拷贝 
        let  newState = JSON.parse(JSON.stringify(state))
        // 2 判断当前点击的商品是否存在购物车中
        let index = state.cards.findIndex(item=>item.id ===action.good.id)
        if(index> -1){
            newState.cards[index].num++
        }else{
            newState.cards.push({
                id:action.good.id,
                name:action.good.name,
                price: action.good.price,
                num: 1
            })
        }
        return newState
    }else if(action.type ==='JIAN_TODO'){
        let newState = Object.assign({},state,{})
        console.log(newState)
        let index = state.cards.findIndex(item =>item.id ===action.good.id)
        if(index > -1){
            if(newState.cards[index].num>1){
                newState.cards[index].num--
            }else{
                newState.cards[index].num=1
            }
            return newState
        }
    }else {
        // 初始化
        return {
          name: '张三',
          cards: [
            {id: 1, name: 'Apple', price: 10, num: 1}
          ]
        }
      }
}
//创建仓库实例  接受reducer
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default store

相关文章

网友评论

      本文标题:Redux实现简单购物车

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