【问题标题】:react button conditional rendering not working反应按钮条件渲染不起作用
【发布时间】:2022-06-25 14:25:52
【问题描述】:

在购物车应用程序上工作 - 问题是当数量被购买时,它应该使按钮被禁用但它不起作用,只显示添加到购物车按钮而不在数量为零时禁用它

import { Button } from 'react-bootstrap';
import { Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useContext } from 'react';
import Rating from './Rating';
import axios from 'axios';
import { Store } from '../Store';

function Product(props){

    const {product} = props;

    const {state , dispatch:ctxDispatch} = useContext(Store);
    const {cart: {cartItems}} = state

    const addToCartHandler = async (item )=>{
      const existItem = cartItems.find((x)=> x._id === product._id);
       const quantity = existItem ? existItem.quantity+1:1 ; 

      const {data} = await axios.get(`/api/products/${item._id}`);
      if(data.countInStock < quantity){
          window.alert('sorry product is out of stock')
          return;
      }
       ctxDispatch({
           type:'CART_ADD_ITEM' 
           , payload:{...item , quantity},
       });
      };
      

    return(

        <Card>


        <Link to={`/product/${product.slug}`}> 
          <img src={product.image} className="card-img-top" alt={product.name} />
        </Link>
        <Card.Body>
        <Link to={`/product/${product.slug}`}>
            <Card.Title>{product.name}</Card.Title>
        </Link>
        <Rating rating={product.rating} numReviews={product.numReviews} />
        <Card.Text>${product.price}</Card.Text>

        {  product.countInStock === 0 ? (

          
          <Button  color="light" disabled={true} >  Out of stock</Button>
          
        ):(
          
          <Button onClick={() => addToCartHandler(product)}>Add to cart</Button>
        )}
      </Card.Body>
    </Card>
    )}

当数量被使用时,它没有显示按钮缺货, 代码有什么问题?

【问题讨论】:

  • 您是否检查过product.countInStock 不是undefined / null/ 0
  • 我在以下行 const quantity = existItem 下添加了控制台 .log ?存在项目.数量+1:1; console.log(product.countInStock) 放在合适的地方吗?

标签: javascript reactjs


【解决方案1】:

你应该确保你正在创建一个新的产品对象,而不是改变旧的。

const product = { ...oldProduct, countInStock: newCountInStock };

而不是

product.countInStock = newCountInStock;

【讨论】:

  • 对不起,我是新来的反应,它不会影响 countInStock 它只是检查它,还是我弄错了?
  • 在这种情况下,如果对象以可变方式更新,则不会触发渲染
【解决方案2】:

问题

认为问题可能出在以下两个地方之一(因为我需要查看您的商店才能确定):

  1. 在商店中(您正在使用有效负载更新您的状态),因为您的 product.countInStock 不知何故未更新。
  2. 在 product.countInStock 数据类型中,因为如果它是字符串或其他内容,它将不起作用

解决方案

在您商店的 product.countInStock 上使用 Chrome 开发工具来检查操作。

说明

由于我们的代码不完整,我来告诉你这个问题的调试策略。

让我们看看算法。

  • 您按下添加到购物车按钮
  • 您将商品(产品)发送到添加到购物车功能中
  • 它检查项目是否已经存在
  • 如果不是,请将商品发送到您的商店
  • 更新您的商店,然后将其作为道具接收(您可以直接接收,我的意思是当您有上下文 API 时为什么要使用道具)
  • 在三元运算符中使用 products 对象

我的猜测是,您正在使用带有添加到购物车按钮的上下文 API(我认为您应该使用 redux,因为 redux 在高频数据流中表现更好)。

现在考虑以下代码:

{product.countInStock === 0 ? (<Button  color="light" disabled={true}>Out of stock</Button>):(<Button onClick={() => addToCartHandler(product)}>Add to cart</Button>)}

开关在 product.countInStock 上。首先检查一下。现在我建议使用 chrome 断点(从 web dev 简化的 YouTube 频道学习,学习断点是救命稻草)来检查它是否正在更新,无论何时单击添加到购物车按钮。您也可以为此目的简单地控制台日志

只需将问题分解为多个部分,然后尝试解决问题所在。问题是您的计数没有以某种方式更新。您在上下文存储中使用的函数有问题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 2022-01-17
  • 2019-03-25
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多