-1

您好,我是新来的反应,并试图通过假商店 API 构建一个结帐系统,用户可以在其中查看购物车中的物品,增加物品的数量,减少物品的数量并清除购物车。到目前为止,我已经在主页上呈现了产品。但我不知道如何增加商品购物车和查看购物车中的商品。我知道这可能是一项简单的任务,但我不知道如何进行,并且我试图避免使用视频教程。请对如何进行的任何建议表示赞赏。


import React from 'react'
import './App.css';
import axios from 'axios'


class App extends React.Component {
  constructor(props) {
      super(props)
      
      this.state = {
          products: [],
          count: 0 
      }
  }
  componentDidMount(){
 axios.get('https://fakestoreapi.com/products')
 .then(response =>{
     const products = response.data
     this.setState({products})
     console.log(products)
 } )
 
 .catch(err=> console.log(err))
  }

  incrementCart = () =>{
 this.setState({count: this.state.count + 1})
  }   
  
  
  render() {
      return (
          <div id="container">
         {
        this.state.products.map(product=> 
             <div id="product" key={product.id}>
              <img className="img" src={product.image} alt="product-store"/>
              <h1>{product.category}</h1>
               <h4>{product.price}</h4>
               <button onClick={this.incrementCart}>Add To Cart</button>
             </div>
            
         )    
         }
         
          </div>

      )
  }
}
export default App

4

2 回答 2

2

最终输出:

在此处输入图像描述

要在单击按钮时将产品存储在购物车中add to cart,我们使用以下addtoCart()函数,该函数将产品对象作为参数。

单击按钮时,将调用此函数,在此函数中,我们将增加购物车项目计数并将提供的product对象添加到我们的cart数组中。

addtoCart = (product) => {
    this.setState({
      count: this.state.count + 1,
      cart: this.state.cart.concat(product)
    });
    console.log(this.state.cart);
  };

现在我们可以使用这两个状态(count和)在下面的代码的帮助下cart使用方法来渲染购物车项目:map

{this.state.products.length > 0 && (
          <div className="cart">
            <p>{this.state.count}</p>
            {this.state.cart?.map((item) => (
              <div className="itemBox">
                <div style={{ marginLeft: 5 }}>
                  <img className="cartImage" src={item.image} />
                </div>
                <div> {item?.title.substr(0, 10) + "..."}</div>
              </div>
            ))}
          </div>
        )}

最终成品源码:

import React from "react";
import "./styles.css";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      products: [],
      count: 0,
      cart: []
    };
  }
  componentDidMount() {
    axios
      .get("https://fakestoreapi.com/products")
      .then((response) => {
        const products = response.data;
        this.setState({ products });
        console.log(products);
      })

      .catch((err) => console.log(err));
  }

  addtoCart = (product) => {
    this.setState({
      count: this.state.count + 1,
      cart: this.state.cart.concat(product)
    });
    console.log(this.state.cart);
  };

  render() {
    return (
      <div>
        <div id="container">
          {this.state.products.length ? (
            this.state.products.map((product) => (
              <div className="productContainer" id="product" key={product.id}>
                <img className="img" src={product.image} alt="product-store" />
                <h1>{product.category}</h1>
                <h4>{product.price}</h4>
                <button onClick={() => this.addtoCart(product)}>
                  Add To Cart
                </button>
              </div>
            ))
          ) : (
            <div className="productContainer">
              <p>Loading</p>
            </div>
          )}
        </div>
        {this.state.products.length > 0 && (
          <div className="cart">
            <p>{this.state.count}</p>
            {this.state.cart?.map((item) => (
              <div className="itemBox">
                <div style={{ marginLeft: 5 }}>
                  <img className="cartImage" src={item.image} />
                </div>
                <div> {item?.title.substr(0, 10) + "..."}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }
}
export default App;

代码沙盒

于 2020-11-27T09:41:35.557 回答
0

与您能够在主页上呈现产品的方式相同,您应该能够对购物车执行相同的操作,但仅更改其呈现方式(布局/模板/组件..)以及关于计数它是什么那你做错了吗?它实际上是在增加吗?如果是这样,您只需将其呈现在正确的位置(您的购物车/导航栏)..

我认为您现在已经完成了几乎相同的工作,但是您只需要在购物车组件上呈现数据吗?然后有办法显示/隐藏该购物车组件?

编辑:

我明白了,我认为您正在增加组件状态,但您没有全局保存该状态,因此您无法在另一个组件/页面或页面刷新后访问它?

我认为您有几个选择,其中之一是发送 GET/POST 请求到 ENDPOINT,它将产品 ID 添加到购物车,而在其他页面/组件中,您必须发送 GET/POST 请求,而不是保存时,将从您之前保存的购物车(产品 ID 与用户连接(例如))中检索数据。

您还可以使用“localStorage”来保存购物车项目/产品数据: https ://developer.mozilla.org/pt-BR/docs/Web/API/Window/Window.localStorage

我猜还有其他选择,但这些对我来说似乎是最简单和最合乎逻辑的解决方案!

于 2020-11-27T09:22:03.490 回答