React Dom 更新状态数组后未更新

React Dom not updating after updating a state array

所以这个函数更新这个状态数组: let [Produits, setProduit] = useState(JSON.parse(Devis.produits))

 let changeQte = (id, e) => {
    let produittable = Produits;
    produittable.forEach((p) => {
      if (p.id == id) {
        p.quantityAchete = parseInt(e.target.value);
      }
    });
    setProduit(produittable);  
  };

阵列更新没有任何问题,但更改没有重新呈现

  {console.log('rendering') ,Produits.map((p) => (
            <div key={p.id} className="product_column flex_center">
              <div className="productItem">{p.nom}</div>
              <div className="productItem">{p.category}</div>
              <div className="productItem">{p.prix_vente} DA</div>
              <input
                onChange={(e) => changeQte(p.id, e)}
                type="number"
                name="qte"
                value={p.quantityAchete}
              />

如您所见,我正在登录控制台以检查该行是否正在执行并且确实执行了!但呈现的值不会更新!

Don't mutate state,改为这样做:

 let changeQte = (id, e) => {
    setProduit(existing => existing.map(c => c.id === id ? {...c,quantityAchete: parseInt(e.target.value)} : c))
  };   

这些行:

    // this line just sets produittable to the same reference as Produits.
    // so now produittable === Produits, it's essentially useless
    let produittable = Produits;
    produittable.forEach((p) => {
      if (p.id == id) {
        // you are mutating 
        p.quantityAchete = parseInt(e.target.value);
      }
    });
    // because produittable === Produits, this doesn't do anything
    setProduit(produittable);  

除了 Adam 所说的,除了不直接修改状态之外,您看不到任何更改的原因是组件仅在状态实际更改时才重新呈现。而要知道状态是否发生了变化,React 对两种状态进行了浅层比较。由于您直接修改了状态,因此引用保持不变,因此您的组件不会重新呈现。