React TS При выведении списка товаров через map производит ошибка
Мне нужно вывести карточки товара с сервера, которым задаю типизацию Product через TS:.
export interface Product{
id: number
title: string
description: string[]
rating: number
price: number
image: string
}
Импортирую и кидаю этот Products в запрос
import { useEffect, useState } from "react";
import Heading from "../../components/Headling/Heading";
import ProductCard from "../../components/ProductCard/ProductCard";
import Search from "../../components/Search/Search";
import { PREFIX } from "../../helper/APi";
import { Product } from "../../interface/product.interface";
import styles from './Menu.module.css';
export default function Menu(){
const [products, setProducts] = useState<Product[]>([])
const getMenu = async() => {
try {
const res = await fetch(PREFIX + '/products')
if (!res.ok){
return
}
const data = await res.json() as Product[];
console.log(data)
setProducts(data)
} catch (e) {
console.error(e)
return
}
}
useEffect(()=>{
getMenu()
},[])
return <>
<div className={styles['head']}>
<Heading>Меню</Heading>
<Search placeholder="Введите блюдо или состав"/>
</div>
<div>
{products.map( (p) => {
<ProductCard
key={p.id}
id = {p.id}
title={p.title}
description={p.description.join(', ')}
rating={p.rating}
price={p.price}
image={p.image}
/>
})}
</div>
</>
}
Данные получены, но почему-то когда я пытаюсь сделать список продуктов через {el.map}, то у меня не получается это сделать, потому что подчеркивается красным и выводится:
(property) ProductCardProps.title: string
Type 'void[]' is not assignable to type 'ReactNode'.
Type 'void[]' is not assignable to type 'Iterable<ReactNode>'.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
Type 'IteratorResult<void, any>' is not assignable to type 'IteratorResult<ReactNode, any>'.
Type 'IteratorYieldResult<void>' is not assignable to type 'IteratorResult<ReactNode, any>'.
Type 'IteratorYieldResult<void>' is not assignable to type 'IteratorYieldResult<ReactNode>'.
Type 'void' is not assignable to type 'ReactNode'.ts(2322)
index.d.ts(2268, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
Сама карточка(компонента)продукта(ProductCard)
import { ProductCardProps } from "./ProductCard.props";
import styles from './ProductCard.module.css';
import { Link } from "react-router-dom";
export default function ProductCard(props:ProductCardProps){
return(
<Link to={`/product/${props.id}`}>
<div className={styles.card}>
<div className={styles.head} style={{backgroundImage: `url('${props.image}')`}}>
<div className={styles.price}>
{props.price}
<span> ₽</span>
</div>
<button className={styles['add-to-card']}>
<img src="./menu/cart-card-btn.png" alt="добавить в корзину" />
</button>
<div className={styles['rating']}>
{props.rating}
<img src="./menu/rating.png" alt="иконка звезды" />
</div>
</div>
<div className={styles.footer}>
<div className={styles['title']}>{props.title}</div>
<div className={styles['description']}>{props.description}</div>
</div>
</div>
</Link>
)
}
Типизация карточки товара(компонента)(ProductCardProps)
export interface ProductCardProps{
id: number;
title: string;
description: string;
rating: number;
price: number;
image: string;
}
Настройки tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Node",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
Настройки tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
типизация для переменных и компонентов должна быть правильной
Ответы (1 шт):
Автор решения: djakuzi
→ Ссылка
В общем, проблему я решил, НЕ ЗАБЫВАЙТЕ в map написать return. Такая глупая ошибка(