Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

change data from array state reactjs

when adding products to cart it can add with quantity.after adding cart i want to change the quantity also from the cart.but it will not change in there anything i need to change in set state.how can i fix this? really appreciate the help

cart.jsx

 const Store = () => {
    const [listData, setListData] = useState({ lists: [] });
   

    useEffect(() => {
        const fetchData = async () => {
            const token = JSON.parse(localStorage.getItem('Token'));
            const body ={token}
            const result = await axios.post(
                'http://localhost:4000/store/cart',body);
            setListData({ lists: result.data });
        };
        fetchData();
    }, []);


   
  
  const onChangeProductData = (e) => {
    setListData({
        ...listData,
        [e.target.name]: e.target.value
    })
    
}


    
    
   
 
  const itemsPrice =  listData.lists.reduce((a, c) => a + c.quantity * c.product_price, 0);;
  const totalPrice = itemsPrice;
  
    return (
        <div className="store">
        <div className="header">
          <a href="/store" className="logo">Milk.Lk</a>
          <div className="menu">
            <div className="dropdown">
              <button className="dropbtn">Category</button>
              <div className="dropdown-content">
                <a href="/freshmilk">FreshMilk</a>
                <a href="#">Link 2</a>
                <a href="#">Link 3</a>
              </div>
            </div>
            <a href="/login">Contact us</a>
          </div>
          <div className="header-right">
            <a href="/register">SingUp</a>
            <a href="/login">Login</a>
          </div>
        </div>
        <div className="container">    
        <div className="cart">
               
        {listData.lists.length === 0 && <div>Cart is empty</div>}
                    {listData.lists.map((current, i) => (
                      
                       <div className='product-cart container'>
        
        
                         <div className="colm1" ><img key={i} className='product-cart-img' src={`http://localhost:4000/uploads/${current.image}`} alt='' /></div>
        
        <div className="colm2" ><a >{current.product_name}</a></div>
        <div className="colm3"><div class="form-group mx-sm-4 mb-2">

<select class="form-control " name="quantity" onChange={onChangeProductData} value={current.quantity} >
  <option value='1'>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>
{current.product_price} Remove ))} Total Price ${totalPrice}
        </div>
        </div>
        
    );
                      
}

export default Store;
question from:https://stackoverflow.com/questions/65856429/change-data-from-array-state-reactjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to update a quantity for a particular product but you're updating listData object, to fix this

First you need to pass some identifier to onChangeProductData if there is id on each product you can pass that or pass index

<select class="form-control " name="quantity" onChange={(ev) => onChangeProductData(ev, i)} value={current.quantity} > // here you can pass some id as well instead of index

Now

const onChangeProductData = (e, i) => {
    const list = [...listData];
    list[i] = {
        ...list[i],
        [e.target.name]: e.target.value
    }
    setListData({
        ...listData,
        list
    })    
}

Above changes will fix your problem:

Suggestion: listData sould be like -

const [listData, setListData] = useState([]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...