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

React setState未更新DOM:商品数量变更不显示如何修复?

React商品数量更新后DOM未同步渲染的修复方案

问题根源

你代码里的核心错误是传递给ProductList组件的是初始静态数组productList,而非维护状态的products变量。点击按钮后状态products确实更新了,但子组件拿到的始终是最初的静态数组,所以DOM不会同步刷新。

另外,虽然你用了数组展开创建新数组,但直接修改数组内对象的属性不符合React的immutable原则(虽不影响本次修复,但建议优化)。

修复步骤

1. 修正传递给子组件的数据源

在App.js的return部分,将ProductList的productList属性值从productList改为状态变量products:

// App.js 中 return 内的 ProductList 组件
<ProductList
  productList={products} // 这里改成状态变量products
  incrementQty={incrementQty}
  decrementQty={decrementQty}
/>

2. 优化状态更新逻辑(可选但推荐)

修改增减数量的函数,对要更新的商品对象也做浅拷贝,保持状态不可变:

const incrementQty = (inx) => {
  let newProductList = [...products];
  // 浅拷贝要修改的商品对象,避免直接修改原对象
  newProductList[inx] = {...newProductList[inx], quantity: newProductList[inx].quantity + 1};
  setState(newProductList);
};

const decrementQty = (inx) => {
  let newProductList = [...products];
  if(newProductList[inx].quantity > 0){
    newProductList[inx] = {...newProductList[inx], quantity: newProductList[inx].quantity - 1};
  }
  setState(newProductList);
};

修改后的完整App.js代码

import "./App.css";
import Navbar from "./components/navbar";
import ProductList from "./components/ProductList";
import Footer from "./components/Footer";
import React, { useState } from "react";

function App() {
  let productList = [
    {
      price: 99999,
      name: "Iphone 10S Max",
      quantity: 0,
    },
    {
      price: 999,
      name: "Realme 9 Pro",
      quantity: 0,
    },
  ];

  let [products, setState] = useState(productList);

  const incrementQty = (inx) => {
    let newProductList = [...products];
    newProductList[inx] = {...newProductList[inx], quantity: newProductList[inx].quantity + 1};
    setState(newProductList);
  };
  
  const decrementQty = (inx) => {
    let newProductList = [...products];
    if(newProductList[inx].quantity > 0){
      newProductList[inx] = {...newProductList[inx], quantity: newProductList[inx].quantity - 1};
    }
    setState(newProductList);
  };

  return (
    <React.StrictMode>
      <Navbar />
      <div className="mt-5">
        <ProductList
          productList={products}
          incrementQty={incrementQty}
          decrementQty={decrementQty}
        />
      </div>
      <Footer />
    </React.StrictMode>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:20:31