简体   繁体   English

如何使用同一页面锚标签隐藏/显示 Next.js 中的内容

[英]How to use same page anchor tags to hide/show content in Next.js

The problem问题

The current project is using Next.js and this situation occurred: the content needs to be hidden or replaced, matching the current category selected.当前项目使用 Next.js 出现这种情况:需要隐藏或替换内容,匹配当前选择的类别。 I want to do it without reloading or using another route to do so.我想在不重新加载或使用其他路线的情况下这样做。 And when the user presses F5 or reloads the page the content remains unchanged.当用户按下 F5 或重新加载页面时,内容保持不变。

The attempts尝试

Next.js' showcase page apparently is able to do so. Next.js 的展示页面显然能够做到这一点。 In the docs, there's a feature called 'Shallow routing' , which basically gives the possibility to update the URL without realoading the page.在文档中,有一个名为“浅路由”的功能,它基本上可以在不重新加载页面的情况下更新 URL。 That's what i figured out for now.这就是我现在想出来的。 Any clues on how the content is changed to match the category?关于如何更改内容以匹配类别的任何线索?

Thanks!谢谢!

You can load the content on the client based on the category passed in the URL fragment ( # value) using window.location.hash .您可以使用window.location.hash根据 URL 片段( #值)中传递的类别在客户端加载内容。

Here's a minimal example of how to achieve this.这是一个如何实现这一目标的最小示例。

import React, { useState, useEffect } from 'react'

const data = {
    '#news': 'News Data',
    '#marketing': 'Marketing Data',
    default: "Default Data"
}

const ShowCasePage = () => {
    const router = useRouter()
    const [categoryData, setCategoryData] = useState()

    const changeCategory = (category) => {
        // Trigger fragment change to fetch the new data
        router.push(`/#${category}`, undefined, { shallow: true });
    }

    useEffect(() => {
        const someData = data[window.location.hash] ?? data.default // Retrieve data based on URL fragment
        setCategoryData(someData);
    }, [router])

    return (
        <>
            <div>Showcase Page</div>
            <button onClick={() => changeCategory('news')}>News</button>
            <button onClick={() => changeCategory('marketing')}>Marketing</button>
            <div>{categoryData}</div>
        </>
    )
}

export default ShowCasePage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM