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

首先,我制作价格 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


慕桂英546537
浏览 79回答 1
1回答

茅侃侃

updatevalue您只需在映射购物车时将索引传递给,并更新price该索引处的数组即可。转换updatevalue为柯里化函数以使用索引并返回事件处理程序。const updatevalue = index => () => {&nbsp; setPrice(prices => prices.map((price, i) => i === index ? price * 2 : price));}...return (&nbsp; <div className='container'>&nbsp; &nbsp; {ShoppingCart.map((products, i)=>( // <-- cart index&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img style={Style} src={products.image} />&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; <span>{price}</span>&nbsp; &nbsp; &nbsp; &nbsp; <span>{quantity}</span>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={updatevalue(i)}>+</button> // <-- pass index to handler&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; ))}&nbsp; </div>)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript