最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Dom not updating after updating a state array - Stack Overflow

programmeradmin0浏览0评论

so this function updates this 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);  
  };

the array did update without any problem but the changes aren't getting re-rendered

  {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}
              />

as you can see i'm loggin to the console to check if that line is getting executed and it does ! but the values rendered doesn't update !

so this function updates this 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);  
  };

the array did update without any problem but the changes aren't getting re-rendered

  {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}
              />

as you can see i'm loggin to the console to check if that line is getting executed and it does ! but the values rendered doesn't update !

Share Improve this question edited Feb 18, 2021 at 14:37 Fares Harmali asked Feb 18, 2021 at 14:33 Fares HarmaliFares Harmali 331 silver badge6 bronze badges 3
  • 1 You're mutating state. Don't mutate state. – Adam Jenkins Commented Feb 18, 2021 at 14:37
  • can you explain ? – Fares Harmali Commented Feb 18, 2021 at 14:38
  • 1 Since the reference to the array didn't change as you modified the state directly, your ponent is not getting rerendered. – jperl Commented Feb 18, 2021 at 14:46
Add a ment  | 

4 Answers 4

Reset to default 4

Don't mutate state, do this instead:

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

These lines:

    // 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);  

To expand on Adam's answer, you can also clone the current state Produits and assign it to the local variable produittable and have the state update be recognized.

So instead of this:

let produittable = Produits;

You could simply clone it like so, with the spread operator:

let produittable = [...Produits];

In addition to what Adam said, besides not modifying the state directly, the reason you're not seeing any changes is because the ponent only gets rerendered when the state actually changed. And to know whether the state changed, react makes a shallow parison between the two states. Since you modified the state directly, the reference remains the same and as such your ponent isn't rerendering.

I was facing the same issue. where I had search ponent and showing list of item in the dropdown. where issue was it was showing items in the list but not in the updated array when I console it.

Fix worked for me was passing unique id as ponent key property. before I was passing name and because of duplicate name it was not removing the items from the DOM.

before:
<li key={item.name}>{item.name}</li>

after:
<li key={item.id}>{item.name}</li>
发布评论

评论列表(0)

  1. 暂无评论