简体   繁体   English

即使不设置值也可以更改useState

[英]useState changing even without setting the value

I am totally confused about this scenario , I am having a state variable called listItems setting the value for listItems using the api call inside useEffect now in the handleChange I am changing the particular object value inside the listItems but I didn't change the actual listItems value but if i console the listItems it's showing as updated value even without setList how come it happens? 我完全糊涂了有关这种情况下,我有一个状态变量称为listItems中设置使用内部useEffect API调用现在我改变了时listItems内部的具体对象值handleChange listItems中的价值,但我并没有改变实际时listItems值,但是如果我管理listItems ,即使没有setList,它也会显示为更新后的值,怎么发生?

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import OrderSummary from './orderSummary'

export default function displayItems() {
  const [listItems, setList] = useState([]);
  const [order, setorder] = useState([]);
  var newarr = [];

  useEffect(() => {
    axios.post('http://localhost:3006/listItem', {

    })
      .then(function (resp) {
        let res = resp.data.sendList.response;
        let newRes = res.map((item) => {
          return item;
        })
        setList(newRes);
      })
      .catch(function (error) {
        console.log(error);
      });

  }, [])

  function handleChange(type,item) {
    var arrList=item;
    var newAr=[];
    if (type === 1) {
      arrList.quantity=arrList.quantity+1;
    }
    else if (type === 0 && item.quantity > 1) {
      arrList.quantity=arrList.quantity-1;
    }
    newAr.push(arrList);
    console.log("test",listItems) // value changes here dont know how
    //  setList(listItems);
  }

  function placeOrder(item) {
    newarr.push(...order, item);
    setorder(newarr)
  }

  return (
    <div className="col">
      <div className="row">
        <div classname="col-md-6">
        <p><b>Available Items</b> </p>
          {listItems && listItems.map((item) => {
            return (
              <div key={item._id}>
                <p>Name:{item.name}</p>
                <p>Description:{item.description}</p>
                <p>Cost:{'₹'}{' '}{item.cost}</p>
                <p>Quantity:{' '}
                  <i onClick={() => handleChange(1,item)} className="fa fa-plus-circle" />
                  <span className="text-center"><b>{item.quantity}</b></span><i onClick={() => handleChange(0,item)} className="fa fa-minus-circle" /></p>
                <div>
                  <button onClick={() => placeOrder(item)}>Add to order</button>
                </div>
              </div>)
          })}
        </div>
        {order && <OrderSummary orderItems={order} />}
      </div>
    </div>
  )
}

sandox sandox

The following code var arrList=item; 下面的代码var arrList=item; is an assignment by reference, it means that arrList and item are both references to the same object which explains the modification of the second when modifying the first, if you want to clone an object you can use Object.assign() or the Spread operator or another solution: 是通过引用分配的,这意味着arrListitem都是对同一对象的引用,这在修改第一个对象时说明了第二个对象的修改,如果要克隆对象,可以使用Object.assign()Spread operator或其他解决方案:

var arrList = Object.assign({}, item);
// Or
var arrList = {...item};

Working demo: 工作演示:

编辑wispy-dawn-xogze

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM