You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React数组在条件不满足时仍存入false值的问题求助

问题分析与解决方案

问题原因

你用map遍历数组时,val.product_quantity > 0 && {...}这个表达式在条件不满足时会返回false,而map会为原数组的每个元素生成一个返回值,所以最终数组里会塞满false而非过滤掉不符合条件的项,导致数组长度始终等于原数组长度,干扰了后续的长度判断逻辑。

另外你的useEffect依赖是空数组,组件挂载后只会执行一次,不会响应Redux中orders数据的变化,这也是潜在的逻辑漏洞。

解决方案

要实现“仅保留符合条件的元素”,可以通过以下两种方式处理:

方案1:filter + map 组合

先通过filter筛选出product_quantity > 0的元素,再用map转换成需要的对象结构,从根源上避免无效值混入数组:

const list = orders
  .filter(val => val.product_quantity > 0)
  .map(val => ({
    id: val.product_id,
    product_name: val.product_name,
    product_title: val.product_title,
    product_price: val.product_price,
    product_quantity: val.product_quantity,
  }));

方案2:使用reduce方法

用reduce遍历数组,仅将符合条件的元素添加到结果数组中,一次遍历完成筛选和转换:

const list = orders.reduce((acc, val) => {
  if (val.product_quantity > 0) {
    acc.push({
      id: val.product_id,
      product_name: val.product_name,
      product_title: val.product_title,
      product_price: val.product_price,
      product_quantity: val.product_quantity,
    });
  }
  return acc;
}, []);

额外优化点

  1. 修正useEffect的依赖数组,添加orders,确保Redux数据变化时重新计算列表:
useEffect(() => {
  // 这里放上面的list生成逻辑
  setOrdersList(list);
}, [orders]);
  1. 无需额外维护isFound状态,直接通过ordersList.length > 0判断即可,简化代码结构。

修改后的完整代码

import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import classes from "./Cart.module.css";

const Cart = () => {
  const navigate = useNavigate();
  const orders = useSelector((state) => state.data.DUMMY_DATA);
  const total = useSelector((state) => state.data.products_total);
  const [ordersList, setOrdersList] = useState([]);

  useEffect(() => {
    // 使用filter + map组合生成目标数组
    const list = orders
      .filter(val => val.product_quantity > 0)
      .map(val => ({
        id: val.product_id,
        product_name: val.product_name,
        product_title: val.product_title,
        product_price: val.product_price,
        product_quantity: val.product_quantity,
      }));
    setOrdersList(list);
  }, [orders]);

  const clickDataHandler = () => {
    // console.log(ordersList);
  };

  return (
    <div className={classes.modal}>
      <div className={classes.root}>
        <span
          className={classes.close}
          onClick={() => navigate("/", { replace: true })}
        >
          &times;
        </span>
        {ordersList.map(
          (data) => (
            <div className={classes.wrapper} key={data.id}>
              <div className={classes.item}>
                Item: &emsp;&emsp;{data.product_name}
              </div>
              <div className={classes.amount}>
                Quantity:&emsp;&emsp; {data.product_quantity}
              </div>
              <div className={classes.price}>
                Price:&emsp;&emsp; {"$" + data.product_price}
              </div>
            </div>
          )
        )}
        {ordersList.length > 0 && (
          <div className={classes.order_button_wrapper}>
            <div className={classes.total}>Total amount:&ensp;{total}</div>
            <button className={classes.order_button} onClick={clickDataHandler}>
              Order
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default Cart;

内容的提问来源于stack exchange,提问作者Ayan Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:35:26