繁体   English   中英

按钮 onClick 在我的反应组件中不起作用

[英]Button onClick is not working in my react component

我正在制作亚马逊克隆产品,但添加到购物车按钮不起作用。 我正在撕裂这是家庭组件,并只从那里获得所有这些道具。 有人,请帮忙。 我只被困在那里2天。 任何帮助表示赞赏。 ???

import React from 'react';
import "./Product.css";
import {useStateValue} from './StateProvider';

function Product({id, title, price, rating, image}) {

    const [state, dispatch] = useStateValue();

    function addToCart(event) {

        console.log(event);

        dispatch({
            type: 'ADD_TO_CART',
            item: {

                id: id,

                title: title,
                image: image,
                price: price,
                rating: rating
            },
        });

    };


   
    return (
        <div className="product">
           
            <div className='product__info'>
                <p>{title}</p>
                <p className='product__price'>
                    <small>₹</small>
                    <strong>{price}</strong>

                </p>
                <div className='product__rating'>
                    {
                        Array(rating)
                            .fill()
                            .map((_, i) => (<p>⭐</p>))
                    }
                </div>
            </div>
            <img src={image} alt=''/>
            <button onClick={addToCart}>Add to cart</button>

        </div>
    );
}

    
export default Product

您需要将调用更新为:

            <button onClick={(event) => { addToCart}}>Add to cart</button>

尝试将您的addToCart function 更改为箭头function:

 const addToCart = (event) => { console.log(event); dispatch({ type: 'ADD_TO_CART', item: { id: id, title: title, image: image, price: price, rating: rating }, }); };

看起来您的代码没有任何问题。 我怀疑useStateValue function 有问题。

我会看几个地方:

  • useStateValue返回的dispatch肯定是调度程序吗?

  • 您的减速器是否正确拾取了“ADD_TO_CART”操作? 可能某处有错别字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM