亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在react js中更新功能組件setState中整數數組的特定索引

如何在react js中更新功能組件setState中整數數組的特定索引

慕桂英546537 2023-09-07 10:05:20
首先,我制作價格 int 數組并僅將 int 數字存儲在鉤子中一次,然后我想在更新值中更新該價格數組的特定索引,但無法更新 setPrice 特定索引,而是將我返回到只有一個值的數組,但我想要所有具有更新索引值的值,如 [0,3,4,5,6] 更新 id 1 然后在我的邏輯中乘以 2 它應該做 [0,6,4,5,6] 但它只返回我 [6]import React, {useEffect,useState,useContext } from 'react';import {Cartlist} from '../Global/CartContext.js';const Cart=()=>{  const {ShoppingCart,totalprice,quantity,dispatch} = useContext(Cartlist);  const [price,setPrice]=useState([])  const Style={    width:'100px',    height: '100px',  }  useEffect(()=>{    ShoppingCart.map((products)=>{      setPrice(prev=>[...prev,products.price]);    })  },[])  const updatevalue=(e)=>{    ShoppingCart.map((products)=>{      if (e.target.id===products.id){          setPrice(price=>price[products.id-1]*2);      }  })  }  return (    <div className='container'>      {ShoppingCart.length > 0 ?        ShoppingCart.map((products)=>(          <div>            <span><img style={Style} src={products.image}></img></span>            <span>{price}</span>            <span>{quantity}</span>            <span><button id={products.id} onClick={updatevalue}>+</button></span>          </div>        ))      :''}    </div>  )}export default Cart
查看完整描述

1 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

updatevalue您只需在映射購物車時將索引傳遞給,并更新price該索引處的數組即可。轉換updatevalue為柯里化函數以使用索引并返回事件處理程序。


const updatevalue = index => () => {

  setPrice(prices => prices.map((price, i) => i === index ? price * 2 : price));

}


...


return (

  <div className='container'>

    {ShoppingCart.map((products, i)=>( // <-- cart index

      <div>

        <span>

          <img style={Style} src={products.image} />

        </span>

        <span>{price}</span>

        <span>{quantity}</span>

        <span>

          <button onClick={updatevalue(i)}>+</button> // <-- pass index to handler

        </span>

      </div>

    ))}

  </div>

)


查看完整回答
反對 回復 2023-09-07
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號