簡體   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