繁体   English   中英

如何在 react.js 中将钩子值从父级传递给子级

[英]How to pass hook value from parent to child in react.js

所以我正在开发一个库存应用程序,将我所有的 class 组件转换为功能组件。但是当我尝试将库存值传递给子元素时,它给了我一个无法设置的错误。map on undefined

这是我的应用组件

const App = () => {

  const [inventory, setInventory] = useState([]);
  const [pointer, setPointer] = useState('')
  const addProduct = (item) => {
    if(inventory.some(product => product.name === item.name)){
      setInventory(
        inventory.map(product => {
          if(product.name === item.name){
            product.quantity += parseInt(item.quantity);
            return product;
          } return product;
        })
      )
      return;
    }
    const newItem = {
      id: uuid(),
      name: item.name,
      quantity: parseInt(item.quantity),
      unit: item.unit
    }
    setInventory(
      ...inventory, newItem
    )
  }
  const updateQuantity = (item)=> {
      // this.Modal.current.toggleModal();
      setPointer(item.id)
  }
  const confirmUpdate = (quantity, pointer) => {
    setInventory(inventory.map(item => {
        if(item.id === pointer){
          item.quantity = quantity;
          return item;
        }
        return item;
      })
    )
  }
  const deleteItem = (id) => {
    setInventory(
      inventory.filter(item => item.id !== id)
    )
  }
  return (
    <div className="App">
      <Header />
      <div className="container">
        <h1 style={{ width: '100%' }}>Inventory</h1>
        <AddItem addProduct={addProduct}/>
        <Inventory updateQuantity={updateQuantity} deleteItem={deleteItem} inventory={inventory}> </Inventory>
      </div>
      <UpdateModal confirmUpdate={confirmUpdate} pointer={pointer}/>
    </div>
  )
}

子组件

const Inventory = props => {
    return (props.inventory.map(item => (
        <Item
        key={item.id}
        updateQuantity={props.updateQuantity}
        deleteItem={props.deleteItem} 
        item={item} 
        />)))
    }

我想要的只是将应用程序组件中的库存值传递给库存组件到 map 它......但我收到以下错误

TypeError: props.inventory.map is not a function

我确定答案很简单,但我被困在谷歌虫洞中,找不到答案......

更新...

由于某种原因,该属性作为 object 而不是数组发送...

无论我做什么,console.log(typeof props.inventory) 总是返回一个 object ...

我尝试了几种方法...

1-将其作为属性值 [...inventory] 内的数组展开,会引发另一个错误

2- 在 useState 挂钩中声明为新的 Array(),仍然没有

3-在属性调用中使用 Array.from(inventory) ,仍然没有..

我是新来的反应,所以一定有我想念的东西

您在此处将数组转换为 Object:

setInventory({
  ...inventory, newItem
})

肯定是:

setInventory([
  ...inventory, newItem
])

所以这就是我做错了......

我更新 function 的钩子有错误的语法,但它没有被反应捕获,因为显然该属性总是作为 object 传递? 我不确定..

无论如何重组我的钩子 function 修复它......

代替

setInventory(
      ...inventory, newItem
    )

它是

setInventory(inventory =>
      [...inventory, newItem]
    )

是的,这解决了它..

暂无
暂无

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

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