[英]How to pass an array from a parent component to child component using props in React Native?
[英]How to pass a json array that comes from backend to child component using props and react hooks?
我正在做一個 react js 項目,但在將元素數組傳遞給子組件時遇到了麻煩。
這是我的代碼:
父組件
{produtoFiltrado.map(produto =>
<div key={produto.id}>
<BoxProduto
arrayIngredientes={[produto.ingredientes]}
/>
</div>
)}
這個數組在我的 Insomnia 請求響應中顯示如下:
{
"id": 1,
"ingredientes": [
{
"id": 5,
"nome": "Eucalyptus",
"score": 10,
"descricao": " ",
"impacto": " ",
"sinonimos": " "
}
]
}
我想做的是 map 這個數組在一個子組件中,像這樣:
子組件
{props.ingredientes.map(ingrediente =>
<ul key={props.ingredientes.id}>
<ol >{props.ingredientes.nome}</ol>
</ul>
)}
(我正在使用功能組件)
但是這段代碼不起作用,我得到“props.ingredientes”未定義的答案
為什么它返回和未定義的值? 我使用相同的結構來傳遞字符串,它工作得很好
假設您的請求響應是您正在使用的對象數組。map 在帶有響應的父組件中。 讓我們說
produtoFiltrado = [
{
"id": 1,
"ingredientes": [
{
"id": 5,
"nome": "Eucalyptus",
"score": 10,
"descricao": " ",
"impacto": " ",
"sinonimos": " "
}
]
},
.....
.....
.....
]
您應該對父組件和子組件進行以下更改
{produtoFiltrado.map(produto => <div key={produto.id}> <BoxProduto arrayIngredientes={produto.ingredientes} /> </div> )}
{props.arrayIngredientes.map(ingrediente => <ul key={ingrediente.id}> <ol >{ingrediente.nome}</ol> </ul> )}
以下是一些可以解決您的問題的更改
// first add a check that `produtoFiltrado` is defined
{produtoFiltrado && produtoFiltrado.length && produtoFiltrado.map(produto =>
<div key={produto.id}>
<BoxProduto
// also remove the extra `[]` from your array
arrayIngredientes={produto.ingredientes}
/>
</div>
)}
然后在您的子組件中還要在映射之前添加一個檢查
{props.arrayIngredientes && props.arrayIngredientes.length && props.arrayIngredientes.map(ingrediente =>
<ul key={ingrediente.id}>
<ol >{ingrediente.nome}</ol>
</ul>
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.