@IIITRIX

Как правильно использовать useState?

Подскажите, пожалуйста, как правильно использовать useState?
В моем случае нужно, чтобы currentLinkLabel менялся в зависимости от pathname из initialState
import { useState } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'

const initialState = [
  { label: 'Книги', pathname: '/' },
  { label: 'Альбомы', pathname: '/album' },
  { label: 'Разное', pathname: '/other' },
]

export default function Navigation() {
  const router = useRouter()
  const [links, setLinks] = useState(initialState)
  const [currentLink, setCurrentLink] = useState('/')
  const changeCurrentLink = pathname => {
    const setCurrentLink = links.find(el => el.pathname === pathname).pathname
  }
  const dropdownLinks =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.filter(el => el.pathname !== currentLink)
      : links.filter(el => el.pathname !== '/')
  const currentLinkLabel =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.find(el => el.pathname === currentLink).label
      : 'Книги'
  const currentLinkPathname =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.find(el => el.pathname === currentLink).pathname
      : '/'
  return (
    <div className='container'>
      <a className='link' href={currentLinkPathname}>
         {currentLinkLabel}
      </a>
       {dropdownLinks.map((link, index) => {
          return (
          <React.Fragment key={index}>
              <Link href={link.pathname}>
                  <a className='item' onClick={changeCurrentLink(link.pathname)}>
                      {link.label}
                  </a>
              </Link>
          </React.Fragment>
          )
       })}
    </div>
  )
}
  • Вопрос задан
  • 98 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы