首页 > 解决方案 > 传递回调函数以在 React 中构建购物车功能

问题描述

我正在尝试建立一个电子商务网站,尝试建立添加到购物车的功能,当我使用道具从组件传递回调函数到父组件时,它似乎不起作用。我找不到任何好的文档。我使用 commercejs 作为后端这是我的产品代码:

import React, { Component } from 'react';
import stripHtml from 'string-strip-html';
import { Card, ListGroup, ListGroupItem, Button} from 'react-bootstrap';

class ProductItem extends Component {
    constructor(props){
        super(props);
        this.handleAddToCart = this.handleAddToCart.bind(this);
    }
    handleAddToCart() {
        this.props.onAddToCart(this.props.product.id, 1);
    }
    render() {
        const { product } = this.props
        const { result } =(product.description);

        return(
            <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src={product.media.source} alt={product.name}  />
                <Card.Body>
                    <Card.Title>{product.name}</Card.Title>
                    <Card.Text>
                    {result}
                    </Card.Text>
                </Card.Body>
                <ListGroup className="list-group-flush">
                    <ListGroupItem>{product.price.formatted_with_symbol}</ListGroupItem>
                    <ListGroupItem>Dapibus ac facilisis in</ListGroupItem>
                </ListGroup>
                <Card.Body>
                    <Button name='Add to cart' className='product__btn' onClick={this.handleAddToCart}>Add to Cart</Button>
                    <Card.Link href="#">Another Link</Card.Link>
                </Card.Body>
                </Card>
        )
    }
}
export default ProductItem;

App.js 文件:

import React, { Component } from 'react';
import { commerce } from './lib/commerce';
import ProductsList from './components/ProductList';
import { Nav, Navbar, Form, FormControl, Button, NavDropdown} from 'react-bootstrap';
class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      products:[],
      cart:{},
    }
  }
  componentDidMount() {
    this.fetchProducts();
    this.fetchCart();
  }
  fetchProducts() {
    commerce.products.list().then((products) => {
      this.setState({products: products.data});
    }).catch((error) => {
      console.log('There was an error fetching the products', error);
    });
  }
  fetchCart() {
    commerce.cart.retrieve().then((cart) => {
      this.setState({ cart });
    }).catch((error) => {
      console.error('There was an error fetching the cart', error);
    });
  }
  handleAddToCart(productId, quantity) {
    commerce.cart.add(productId, quantity).then((item) => {
      this.setState({cart: item.cart})
    }).catch((error) => {
      console.error('There was an error adding the item to the cart', error);
    });
  }
  render() {
    const { products } = this.state;
    return(
      <div className='App'>
        <Navbar bg="light" expand="lg">
        <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="mr-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#link">Link</Nav.Link>
            <NavDropdown title="Dropdown" id="basic-nav-dropdown">
              <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
            </NavDropdown>
          </Nav>
          <Form inline>
            <FormControl type="text" placeholder="Search" className="mr-sm-2" />
            <Button variant="outline-success">Search</Button>
          </Form>
        </Navbar.Collapse>
      </Navbar>
        <ProductsList products={products} onAddToCart={this.handleAddToCart}/>
      </div>
    )
  }
}

export default App;

标签: javascriptreactjse-commerce

解决方案


您实际上没有调用产品列表组件中的函数吗?有同样的理由吗?您甚至需要在子组件中调用该函数,仅发送它无济于事。

编辑:您尚未在父组件中绑定该功能。将 handleAddToCart(params) 替换为 handleAddToCart=(params)=> 并且代码应该可以工作


推荐阅读