Не удается прочитать свойство (React)
Консоль выдает ошибку Cannot read properties of undefined (reading 'name')
Мой код:
import React from 'react';
import Categories from '../Categories/Categories';
import GuitarBlock from '../GuitarBlock/GuitarBlock';
import Sort from '../Sort/Sort';
function Home({ guitarItems }) {
return (
<div className='container'>
<div className='content__top'>
<Categories
items={['Gibson', 'Jackson', 'Dean', 'Fender', 'Ibanez']}
/>
<Sort
items={[
{ name: 'популярности', type: 'popular' },
{ name: 'цене', type: 'price' },
{ name: 'алфавиту', type: 'alphabet' },
]}
/>
</div>
<h2 className='content__title'>Все инструменты</h2>
<div className='content__items'>
{guitarItems.map(obj => (
<GuitarBlock key={obj.id} {...obj} />
))}
</div>
</div>
);
}
export default Home;
Жалуется на строку 7 (activeLabel). На то, что не видит свойство name у items.
import React, { useState, useEffect, useRef } from 'react';
function Sort({ items }) {
const [activeItem, setActiveItem] = useState(null);
const [visiblePopUp, setVisiblePopUp] = useState(false);
const sortRef = useRef();
const activeLabel = items[activeItem].name;
const toggleVisiblePopUp = () => {
setVisiblePopUp(!visiblePopUp);
};
const handleOutSideClick = e => {
if (!e.path.includes(sortRef.current)) {
setVisiblePopUp(false);
}
};
const onSelectItem = index => {
setActiveItem(index);
setVisiblePopUp(false);
};
useEffect(() => {
document.body.addEventListener('click', handleOutSideClick);
}, []);
return (
<div ref={sortRef} className='sort'>
<div onClick={toggleVisiblePopUp} className='sort__label'>
<svg
className={visiblePopUp ? 'rotated' : ''}
width='10'
height='6'
viewBox='0 0 10 6'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<path
d='M10 5C10 5.16927 9.93815 5.31576 9.81445 5.43945C9.69075 5.56315 9.54427 5.625 9.375 5.625H0.625C0.455729 5.625 0.309245 5.56315 0.185547 5.43945C0.061849 5.31576 0 5.16927 0 5C0 4.83073 0.061849 4.68424 0.185547 4.56055L4.56055 0.185547C4.68424 0.061849 4.83073 0 5 0C5.16927 0 5.31576 0.061849 5.43945 0.185547L9.81445 4.56055C9.93815 4.68424 10 4.83073 10 5Z'
fill='#2C2C2C'
/>
</svg>
<b>Сортировка по:</b>
<span>{activeLabel}</span>
</div>
{visiblePopUp && (
<div className='sort__popup'>
<ul onClick={toggleVisiblePopUp}>
{items &&
items.map((obj,index)=> (
<li
className={
activeItem === index ? 'active' : ''
}
onClick={() => {
onSelectItem(index);
}}
key={obj.type}
>
{obj.name}
</li>
))}
</ul>
</div>
)}
</div>
);
}
export default Sort;
Ответы (1 шт):
Автор решения: vanesicks
→ Ссылка
У вас в переменной activeItem по умолчанию задается null.
Вы обращаетесь к элементу массива с ключем null – items[null].
Такого элемента у вас нет, поэтому возвращается undefined.
Возможно вам стоит задать useState(0) для activeItem, тогда будет браться первый элемент.