Guest User

Untitled

a guest
Jul 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. // Cart.js
  2.  
  3. import React, {Component} from "react";
  4. import PropTypes from "prop-types";
  5.  
  6. import CartList from "./CartList";
  7. import CartSummary from "./CartSummary";
  8.  
  9. export default class Cart extends Component {
  10. constructor(props) {
  11. super(props);
  12.  
  13. this.state = {
  14. items: [
  15. {id: 1, name: 'P1', price: 100, qty: 1}
  16. ],
  17. amount: 0, // sum of all items price * qty
  18. count: 0, // sum of all items qty
  19. flag: true
  20. }
  21. }
  22.  
  23. addItem = () => {
  24. let id = Math.ceil(Math.random() * 10000);
  25. let item = {
  26. id,
  27. name: `Product ${id}`,
  28. price: Math.ceil(Math.random() * 100),
  29. qty: 1
  30. }
  31.  
  32. //TODO:
  33.  
  34. }
  35.  
  36. removeItem = (id) => {
  37. //TODO
  38. }
  39.  
  40. updateItem = (id, qty) => {
  41. //TODO
  42. }
  43.  
  44. empty = () => {
  45. //TODO
  46.  
  47. }
  48.  
  49. //dummy
  50. refresh = () => {
  51. this.setState({
  52. flag: true
  53. })
  54. }
  55.  
  56. // derived data from state
  57. recalculate(items) {
  58. let count = 0,
  59. amount = 0;
  60.  
  61. for (let item of items) {
  62. amount += item.price * item.qty;
  63. count += item.qty;
  64. }
  65.  
  66. this.setState({
  67. amount,
  68. count
  69. })
  70. }
  71.  
  72. //TODO:
  73. //componentWillMount
  74.  
  75.  
  76. render() {
  77. console.log("Cart render")
  78. return (
  79. <div>
  80. <h2>Cart</h2>
  81.  
  82. <button onClick={this.addItem}>
  83. Add Item
  84. </button>
  85.  
  86.  
  87. <button onClick={this.empty}>
  88. Empty
  89. </button>
  90.  
  91. <button onClick={this.refresh}>
  92. Refresh
  93. </button>
  94.  
  95.  
  96. <CartList items={this.state.items}
  97. removeItem={this.removeItem}
  98. />
  99.  
  100. <CartSummary amount={this.state.amount}
  101. count = {this.state.count}
  102. />
  103.  
  104. </div>
  105. )
  106. }
  107. }
  108.  
  109.  
  110. Cart.defaultProps = {
  111.  
  112. }
  113.  
  114. Cart.propTypes = {
  115.  
  116. }
Add Comment
Please, Sign In to add comment