第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

慕桂英546537 2023-09-07 10:05:20
首先,我制作價(jià)格 int 數(shù)組并僅將 int 數(shù)字存儲在鉤子中一次,然后我想在更新值中更新該價(jià)格數(shù)組的特定索引,但無法更新 setPrice 特定索引,而是將我返回到只有一個(gè)值的數(shù)組,但我想要所有具有更新索引值的值,如 [0,3,4,5,6] 更新 id 1 然后在我的邏輯中乘以 2 它應(yīng)該做 [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貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊

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


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>

)


查看完整回答
反對 回復(fù) 2023-09-07
  • 1 回答
  • 0 關(guān)注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號