美文网首页
React 购物车案例

React 购物车案例

作者: coderhzc | 来源:发表于2021-04-11 16:53 被阅读0次

    0. reduce 高阶函数的使用

      // 实现总价计算
          getTotalPrice() {
            // 第一种实现的方式
            // let totalPrice = 0
            // for(let item of this.state.books){
            //   totalPrice += item.price *item.count
            // }
            // // retur n totalPrice
            // return formatPrice(totalPrice)
    
            // 第二种实现的方式 
            // reduce(回调函数,初始化的值)
            // 参数一: 上一次回调函数的结果(第一次没有上一次函数的回调结果,使用初始化值)
            // 参数二: 当前遍历的项,
            // 参数三: 当前的索引
            // 参数四: 当前的数组
            // reduce((前一次的回调函数的结果,item,index,arr)=> {
    
            //},0)
            const totalPrice = this.state.books.reduce((preValue, item,index,arr) => {
              return preValue + item.count * item.price
            }, 0)
    
            return formatPrice(totalPrice)
          }
    
    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
        table {
          border: 1px solid #eeee;
          border-collapse: collapse;
        }
    
        th,
        td {
          border: 1px solid #eeee;
          padding: 10px 16px;
        }
    
        th {
          background-color: #aaa;
          text-align: center;
          border-color: #ccc;
        }
    
        tr {
          text-align: center;
        }
      </style>
    </head>
    
    <body>
      <div id="root"></div>
      <script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
      <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>
      <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
      <script src="./format-utils.js"></script>
      <script type="text/babel">
        class App extends React.Component {
          constructor(porps) {
            super(porps)
            this.state = {
              books: [
                {
                  id: 1,
                  name: '<<算法论>>',
                  data: '2006-9',
                  price: 59.00,
                  count: 1
                },
                {
                  id: 2,
                  name: '<<Unix编程艺术>>',
                  data: '2006-9',
                  price: 77.00,
                  count: 1
                },
                {
                  id: 3,
                  name: '<<活着>>',
                  data: '2006-9',
                  price: 88.00,
                  count: 1
                },
                {
                  id: 4,
                  name: '<<编程珠玑>>',
                  data: '2006-9',
                  price: 22.00,
                  count: 1
                }
              ]
            }
          }
          //把render函数中的模块剪切掉(这个是当条件满足的时候显示的代码)
          renderBooks() {
            return (
              <div>
                <table>
                  <thead>
                    <tr>
                      <th></th>
                      <th>书籍名称</th>
                      <th>出版日期</th>
                      <th>价格</th>
                      <th>购买数量</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {
                      this.state.books.map((item, index) => {
                        return (
                          <tr>
                            <td>{index + 1}</td>
                            <td> {item.name} </td>
                            <td> {item.data} </td>
                            <td> {formatPrice(item.price)} </td>
                            <td>
                              <button disabled={item.count<1} onClick={e => this.changeOnClick(index,-1)}> - </button>
                              <span> {item.count} </span>
                              <button onClick={e => this.changeOnClick(index,1)}> + </button>
                            </td>
    
                            <td>
                              <button onClick={e => this.removeItem(index)}>移除</button>
                            </td>
                          </tr>
                        )
                      })
                    }
                  </tbody>
                </table>
    
                {/*<h2>总价格: { formatPrice(this.getTotalPrice()) } 元 </h2>*/}
                <h2>总价格: {this.getTotalPrice()} 元 </h2>
              </div>
            )
          }
    
    
          // 这个是当条件不满足的是时候 显示的代码
          renderEmptyTip() {
            return <h2>购物车为空~~~</h2>
          }
    
          render() {
            return this.state.books.length ? this.renderBooks() : this.renderEmptyTip();
          }
    
          // 实现总价计算
          getTotalPrice() {
            // 第一种实现的方式
            // let totalPrice = 0
            // for(let item of this.state.books){
            //   totalPrice += item.price *item.count
            // }
            // // retur n totalPrice
            // return formatPrice(totalPrice)
    
            // 第二种实现的方式
            const totalPrice = this.state.books.reduce((preValue, item) => {
              return preValue + item.count * item.price
            }, 0)
    
            return formatPrice(totalPrice)
          }
    
          //移除书籍
          removeItem(index) {
            console.log(index);
            this.setState({
              books: this.state.books.filter((item, indey) => index != indey)
            })
          }
          
          // 格式化
          function formatPrice(price) {
            if(typeof price !=="number") {
              price = Number(price) || 0
          } 
         return "¥" + price.toFixed(2)
    }
    
        
          // 点击按钮的增加或者减少
          changeOnClick(index,count) {
            //第一种方案
            const newBooks = [...this.state.books]
            newBooks[index].count += count
            this.setState({
              //第一种方案
              books: newBooks
    
            })
          }
    
        }
        ReactDOM.render(<App />, document.querySelector("#root"))
      </script>
    </body>
    
    </html>
    

    实际截图效果

    image.png

    相关文章

      网友评论

          本文标题:React 购物车案例

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