R
R
Roman Andreevich2020-04-29 07:43:06
JavaScript
Roman Andreevich, 2020-04-29 07:43:06

Why is the useRouter NextJS page reloading?

I started making breadcrumbs, everything works, but when you click on any link, the page reloads. What is the reason?

The code:

'use strict';
import { routes } from '../../config'
import articles from '../../articles'
import {useRouter} from 'next/router'
import Link from 'next/link'

export default props => {

    const { asPath } = useRouter()
    const routesArray = asPath.split('/')

    const breadcrumbs = Array.from(new Set(routesArray.map((item) => {
        let path = item === `` ? `/` : `/${item}`
        let part = Object.values(routes).find(item => item.href === path)

        if (!part) {
            const article = articles.find(art => art.id === +item)
            if (article) {
                const { id, title } = article
                return {
                    href: `/articles/[id]`,
                    as: `/articles/${id}`,
                    title
                }
            }
        } else return part

    })))

    return <div className="breadcrumbs"><ul>{
        breadcrumbs.map(({ title, href, as }, index, arr) => (index === arr.length -1)
            ? <li key={index}><span>{ title }</span></li>
            : <li key={index}>
                <Link href={href} as={as}>
                    <a>{ title }</a>
                </Link>
            </li>
        )
    }</ul></div>
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Andreevich, 2020-04-29
@RomanDillerNsk

iordania , yes it's legal, according to the documentation. The problem starts when:

return <div className="breadcrumbs"><ul>{
        breadcrumbs.map(({ title, href, as }, index, arr) => (index === arr.length -1)
            ? <li key={index}><span>{ title }</span></li>
            : <li key={index}>
                <Link href={href} as={as}>
                    <a>{ title }</a>
                </Link>
            </li>
        )
    }</ul></div>

I use title href or as. If you remove it from all the rules, the page simply changes the content. I can't understand why this is happening. I do not change the state of the router or some other parameters.
Thank you all, the issue has been resolved, probably you need to get into the NextJs code and see how everything works there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question