[英]Cannot reach datas details with map function
function Clothes() {
const { loading, error, data } = useQuery(GET_CLOTHES);
const [products,setProducts] = useState([]);
const [index,setIndex] = useState(0)
useEffect(() => {
if (data) {
setProducts(data.AllItem);
console.log(data.AllItem)
}
},[data,products]);
/*
useEffect(() => {
if(!loading && data){
setProducts(data);
}
}, [loading, data])
*/
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
return (
<section className='section'>
<div className='title'>
<h2>
</h2>
{
products?.map((product,index) => {
//const {gallery} = product;
return <img src = {product.gallery} />
})
}
</div>
</section>
)
}
export default Clothes;
大家好,我對 map function 有疑問。我正在從我的 graphql 獲取數據,但是當我試圖在我的 console.log 中獲取它們時,我只能看到未定義。 先感謝您
嘗試將數據直接設置為產品 state(刪除數組),如下所示:
const [products,setProducts] = useState(data);
一些指針可能會有所幫助
transform the reponse and filter the items as needed
const { loading, error, data = [] } = useQuery(GET_CLOTHES);
const [products,setProducts] = useState(data);
const [index,setIndex] = useState(0)
const transformedResponse = useMemo(() => {
try {
// put checks and use try catch to handle errors
const productsList = [];
// check for null data
const items = data ?? []
for (const category of items) {
const products = category?.products ?? [];
productsList.push(...products)
}
return productsList
} catch(error) {
// log error
return []
}
}, [data)]
return (
...
{
transformedResponse.map(prod => {
return (<Prod key={prod.id} {...prod} />)
}
}
)
有關使用 arrays 的文檔
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.