简体   繁体   English

在子组件中改变父数组

[英]Mutate parent array in child component

So I have the following array in my parent, which I fetch from an API:所以我在我的父母中有以下数组,我从 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?我的问题是,我 go 如何在不发送整个 productData 和 setProductData 挂钩的情况下递增和递减 orderedQuantity? 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?有什么方法可以改变父数组,而无需在 productData 中专门搜索该产品并在子组件中使用 setProductData 设置新数组?

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.我需要提及的是,我需要计算父组件中所有订购产品的总价,因此我希望在 productData 中拥有正确的 orderedQuantity。

Send the behavior as a callback to the child.将行为作为回调发送给孩子。

Minimal example of updating a parent with a list on state from a child:使用子项 state 上的列表更新父项的最小示例:

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)} />); 
};

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

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