如何在React中捕获onChange事件时更新输入值?

huangapple go评论82阅读模式
英文:

How to update the input value when catching an onChange event in React?

问题

I am having problems with the total number of items in the CartHeader component. Obviously I have added the quantity of each product but the result is not as I expected ?. Can someone find the fault for me? I sincerely thank.

  1. import CartHeader from "./CartHeader";
  2. import CartBody from "./CartBody";
  3. import CartFooter from "./CartFooter";
  4. import "./styles.css";
  5. class App extends React.Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. products: [
  10. {
  11. id: 1,
  12. name: "Apple Watch Series 5",
  13. description: "Description for Apple Watch Series 5",
  14. img:
  15. "https://bachlongmobile.com/media/catalog/product/cache/2/image/040ec09b1e35df139433887a97daa66f/2/0/2076130625_1_1_1.jpg",
  16. price: 499.99,
  17. quantity: 1
  18. },
  19. {
  20. id: 2,
  21. name: "iPhone 11 Pro Max",
  22. description: "Description for iPhone 11 Pro Max",
  23. img:
  24. "https://cdn.fptshop.com.vn/Uploads/Originals/2019/9/11/637037687763926758_11-pro-max-xanh.png",
  25. price: 1099.99,
  26. quantity: 1
  27. },
  28. {
  29. id: 3,
  30. name: "Macbook Pro 16 inch",
  31. description: "Description for Macbook Pro 16 inch",
  32. img: "https://shopdunk.com/wp-content/uploads/2019/11/mac16inch.jpg",
  33. price: 2399.99,
  34. quantity: 1
  35. },
  36. {
  37. id: 4,
  38. name: "iPad Pro 12.9 inch",
  39. description: "Description for iPad Pro",
  40. img:
  41. "https://cdn.fptshop.com.vn/Uploads/Originals/2019/1/11/636828015979564724_ipad-pro-12-9-xam-1.png",
  42. price: 999.99,
  43. quantity: 1
  44. },
  45. {
  46. id: 5,
  47. name: "AirPods Pro",
  48. description: "Description for AirPods Pro",
  49. img:
  50. "https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/MWP22?wid=1144&hei=1144&fmt=jpeg&qlt=80&op_usm=0.5,0.5&.v=1572990352299",
  51. price: 249.99,
  52. quantity: 1
  53. }
  54. ]
  55. };
  56. }
  57. onRemoveProduct = id => {
  58. const newProducts = this.state.products;
  59. // Find the index of the product to be removed
  60. let index = newProducts.findIndex(product => product.id === id);
  61. // Check if found, then remove it
  62. if (index !== -1) {
  63. newProducts.splice(index, 1);
  64. this.setState({
  65. products: newProducts
  66. });
  67. }
  68. };
  69. handleChange = (e, id) => {
  70. const { products } = this.state;
  71. const indexProduct = products.findIndex(product => product.id === id);
  72. products[indexProduct].quantity = e.target.value;
  73. this.setState({ products });
  74. };
  75. render() {
  76. const products = this.state.products;
  77. let numberItems = 0;
  78. let subTotal = 0;
  79. products.map(product => {
  80. numberItems += product.quantity;
  81. subTotal += product.price * product.quantity;
  82. });
  83. return (
  84. <main>
  85. <CartHeader numberItems={numberItems} />
  86. <CartBody
  87. products={products}
  88. onRemoveProduct={this.onRemoveProduct}
  89. handleChange={this.handleChange}
  90. />
  91. <CartFooter subTotal={subTotal} />
  92. </main>
  93. );
  94. }
  95. }
  96. export default App;
  97. const rootElement = document.getElementById("root");
  98. ReactDOM.render(<App />, rootElement);
英文:

I am having problems with the total number of items in the CartHeader component. Obviously I have added the quantity of each product but the result is not as I expected ?. Can someone find the fault for me? I sincerely thank.

  1. import CartHeader from &quot;./CartHeader&quot;;
  2. import CartBody from &quot;./CartBody&quot;;
  3. import CartFooter from &quot;./CartFooter&quot;;
  4. import &quot;./styles.css&quot;;
  5. class App extends React.Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. products: [
  10. {
  11. id: 1,
  12. name: &quot;Apple Watch Series 5&quot;,
  13. description: &quot;Description for Apple Watch Series 5&quot;,
  14. img:
  15. &quot;https://bachlongmobile.com/media/catalog/product/cache/2/image/040ec09b1e35df139433887a97daa66f/2/0/2076130625_1_1_1.jpg&quot;,
  16. price: 499.99,
  17. quantity: 1
  18. },
  19. {
  20. id: 2,
  21. name: &quot;iPhone 11 Pro Max&quot;,
  22. description: &quot;Description for iPhone 11 Pro Max&quot;,
  23. img:
  24. &quot;https://cdn.fptshop.com.vn/Uploads/Originals/2019/9/11/637037687763926758_11-pro-max-xanh.png&quot;,
  25. price: 1099.99,
  26. quantity: 1
  27. },
  28. {
  29. id: 3,
  30. name: &quot;Macbook Pro 16 inch&quot;,
  31. description: &quot;Description for Macbook Pro 16 inch&quot;,
  32. img: &quot;https://shopdunk.com/wp-content/uploads/2019/11/mac16inch.jpg&quot;,
  33. price: 2399.99,
  34. quantity: 1
  35. },
  36. {
  37. id: 4,
  38. name: &quot;iPad Pro 12.9 inch&quot;,
  39. description: &quot;Description for iPad Pro&quot;,
  40. img:
  41. &quot;https://cdn.fptshop.com.vn/Uploads/Originals/2019/1/11/636828015979564724_ipad-pro-12-9-xam-1.png&quot;,
  42. price: 999.99,
  43. quantity: 1
  44. },
  45. {
  46. id: 5,
  47. name: &quot;AirPods Pro&quot;,
  48. description: &quot;Description for AirPods Pro&quot;,
  49. img:
  50. &quot;https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/MWP22?wid=1144&amp;hei=1144&amp;fmt=jpeg&amp;qlt=80&amp;op_usm=0.5,0.5&amp;.v=1572990352299&quot;,
  51. price: 249.99,
  52. quantity: 1
  53. }
  54. ]
  55. };
  56. }
  57. onRemoveProduct = id =&gt; {
  58. const newProducts = this.state.products;
  59. // T&#236;m vị tr&#237; sản phẩm cần xo&#225;
  60. let index = newProducts.findIndex(product =&gt; product.id === id);
  61. // Kiểm tra nếu t&#236;m thấy th&#236; mới xo&#225;
  62. if (index !== -1) {
  63. newProducts.splice(index, 1);
  64. this.setState({
  65. products: newProducts
  66. });
  67. }
  68. };
  69. handleChange = (e, id) =&gt; {
  70. const { products } = this.state;
  71. const indexProduct = products.findIndex(product =&gt; product.id === id);
  72. products[indexProduct].quantity = e.target.value;
  73. this.setState({ products });
  74. };
  75. render() {
  76. const products = this.state.products;
  77. let numberItems = 0;
  78. let subTotal = 0;
  79. products.map(product =&gt; {
  80. numberItems += product.quantity;
  81. subTotal += product.price * product.quantity;
  82. });
  83. return (
  84. &lt;main&gt;
  85. &lt;CartHeader numberItems={numberItems} /&gt;
  86. &lt;CartBody
  87. products={products}
  88. onRemoveProduct={this.onRemoveProduct}
  89. handleChange={this.handleChange}
  90. /&gt;
  91. &lt;CartFooter subTotal={subTotal} /&gt;
  92. &lt;/main&gt;
  93. );
  94. }
  95. }
  96. export default App;
  97. const rootElement = document.getElementById(&quot;root&quot;);
  98. ReactDOM.render(&lt;App /&gt;, rootElement);

have I ever misunderstood the problem. Link codesandbox: https://codesandbox.io/s/thirsty-hill-6w2ex

答案1

得分: 0

The problem is that you are using the + with strings. So when you calculate the total number, you get strange results:

  1. const result = '1' + '1' + '2'
  2. console.log(result) // '112'

Change the render method to:

  1. products.map(product => {
  2. numberItems += Number(product.quantity);
  3. console.log(numberItems);
  4. subTotal += Number(product.price) * Number(product.quantity);
  5. });
英文:

The problem is that you are using the + with strings. So when you calculate the total number, you get strange results:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const result = &#39;1&#39; + &#39;1&#39; + &#39;2&#39;
  2. console.log(result) // &#39;112&#39;

<!-- end snippet -->

Change the render method to:

  1. products.map(product =&gt; {
  2. numberItems += Number(product.quantity);
  3. console.log(numberItems);
  4. subTotal += Number(product.price) * Number(product.quantity);
  5. });

答案2

得分: 0

  1. handleChange = (e, id) => {
  2. const { products } = this.state;
  3. const indexProduct = products.findIndex(product => product.id === id);
  4. products[indexProduct].quantity = Number(e.target.value);
  5. this.setState({ products });
  6. };

https://codesandbox.io/s/loving-hertz-vfpjw

英文:
  1. handleChange = (e, id) =&gt; {
  2. const { products } = this.state;
  3. const indexProduct = products.findIndex(product =&gt; product.id === id);
  4. products[indexProduct].quantity = Number(e.target.value);
  5. this.setState({ products });
  6. };

https://codesandbox.io/s/loving-hertz-vfpjw

答案3

得分: 0

需要在map循环内返回值。

英文:

you need to return value inside map loop

  1. products.map(product =&gt; {
  2. numberItems += product.quantity;
  3. subTotal += product.price * product.quantity;
  4. return { numberItems, subTotal }
  5. });

huangapple
  • 本文由 发表于 2020年1月6日 23:36:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定