简体   繁体   中英

Mutate parent array in child component

So I have the following array in my parent, which I fetch from an API:

[
  {
    "id": 1,
    "name": "Mars",
    "price": 2.99,
    "availableCount": 6
  },
  {
    "id": 2,
    "name": "Roshen",
    "price": 3,
    "availableCount": 14
  },
  {
    "id": 3,
    "name": "Kinder",
    "price": 2.99,
    "availableCount": 65
  },
]

And the parent component is this:

const Checkout = () => {
  const [productData, setProductData] = useState([]);

  useEffect(() => {
    Promise.resolve(getProducts()).then((result) => {
      setProductData(result);
    });
  },[]);

return (
  productData.map(product => {
    return <Product
      key={product.id}
      id={product.id}
      name={product.name}
      availableCount={product.availableCount}
      orderedQuantity={product.orderedQuantity}
      price={product.price}
      total={product.total}
    />
  })
  //further down, I calculate total price based on ordered products
)

};

The child component has the following definition:

const Product = ({ id, name, availableCount, price, orderedQuantity, total }) => {
  //need to be able to add or subtract orderedQuantity with user input in this component
}

My problem is, how would I go around incrementing and decrementing orderedQuantity without sending down the whole productData and the setProductData hook? Is there any way to mutate the parent array without specifically searching for that product in the productData and setting a new array with setProductData in the child component?

I need to mention that I need to calculate the total price of all ordered products in my parent component, so that's why I would like to have the right orderedQuantity in the productData.

Send the behavior as a callback to the child.

Minimal example of updating a parent with a list on state from a child:

const P = () => {
  const [l, setL] = useState([{id: 1, count: 10}]);
  const remove = id => setL(l.filter(e => e.id === id));
  const inc = id => setL(l.map(e => e.id === id ? ({...e, count: e.count+1}) : e));
  
  // remove={() => remove(e.id)} is the key bit
  return l.map(e => <C id={e.id} remove={() => remove(e.id)} inc={() => inc(id)} />); 
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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