next.js:将数据传递到嵌套路由

发布于 2025-01-27 08:59:23 字数 1368 浏览 2 评论 0原文

问题:

目前,我有一个动态路由,可以使用getServersideProps()获取数据。在此页面中,有多个选项卡会根据状态(选择哪个选项卡)呈现不同的数据。

我希望从使用此页面上的多个选项卡过渡到使用嵌套路由。但是,我很难获得最初在这些嵌套路线中获取的数据。有没有有效的方法,而无需再次致电GetServersideProps()?

我的预期设置看起来像这样,其中[PAGE]调用GetServersIdeProps():

[page].jsx
|_tab1.jsx
|_tab2.jsx
|_tab3.jsx

我的当前[page] .jsx,我想在其中使用可以访问这些道具的单独的嵌套页面(而不是基于状态渲染每个选项卡) :

export default function Page(props) {
    const [currentTab, setCurrentTab] = useState("home");

    return (
        <div>
            <div id="tab1" onClick={() => setCurrentTab("home")}>
                home
            </div>
            <div id="tab2" onClick={() => setCurrentTab("posts")}>
                posts
            </div>
            <div id="tab3" onClick={() => setCurrentTab("info")}>
                info
            </div>

            {currentTab === "home" ? (
                <HomeTab props={props}/>
            ) : currentTab === "posts" ? (
                <PostsTab props={props}/>
            ) : (
                <InfoTab props={props}/>
            )}
        </div>
    );
}

我尝试

  • 使用上下文API尝试在全球使用数据,而我的其他页面可以使用该数据。但是,这要求用户首先访问原始动态路线。
  • 在每个嵌套路线上调用getServersideProps()。尽管这有效,但我希望找到一个更好的解决方案,因为我在每个嵌套的路线上获取数据,而它们嵌套的路线已经有所有这些数据。

Issue:

Right now, I have a dynamic route that fetches data using getServerSideProps(). Within this page, there are multiple tabs that renders different data depending on state (which tab is selected).

I wish to transition from using multiple tabs on this page, to instead using nested routes. However, I am having difficulty obtaining the data originally fetched in these nested routes. Is there an efficient way of doing so, without having to call getServerSideProps() again?

My intended setup looks like this, where [page] calls getServerSideProps():

[page].jsx
|_tab1.jsx
|_tab2.jsx
|_tab3.jsx

My current [page].jsx, where I would like to use separate, nested pages that have access to these props (instead of rendering each tab based on state):

export default function Page(props) {
    const [currentTab, setCurrentTab] = useState("home");

    return (
        <div>
            <div id="tab1" onClick={() => setCurrentTab("home")}>
                home
            </div>
            <div id="tab2" onClick={() => setCurrentTab("posts")}>
                posts
            </div>
            <div id="tab3" onClick={() => setCurrentTab("info")}>
                info
            </div>

            {currentTab === "home" ? (
                <HomeTab props={props}/>
            ) : currentTab === "posts" ? (
                <PostsTab props={props}/>
            ) : (
                <InfoTab props={props}/>
            )}
        </div>
    );
}

Attempts

  • I've attempted using the context API to utilize data globally, which my other pages can use. However, this requires the user to visit the original dynamic route first.
  • Call getServerSideProps() on each nested route. Although this works, I wish to find a better solution, since I'm fetching data on each nested route while the route they're nested under has all of this data available already.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云之铃。 2025-02-03 08:59:23

您可以使用 shallow路由 /docs/api-reference/next/router“ rel =“ nofollow noreferrer”> next/route next/link

请注意,在下面的示例中,我使用next/link 进行演示。没有您的标签数据,我假设您在数据中有一系列标签

import { useEffect } from 'react'
import Link from 'next/link'

//the path is `/tab/:tabId`
function Tab({ data }) {
  const [tabData, setTabData] = useState(data[0]) //first tab data as default for example

  useEffect(() => {
    setTabData(data[tabId])
  }, [router.query.tabId])

  return <>
     <Link href="/tab/0" shallow />
     <Link href="/tab/1" shallow />
     <div>
        {tabData}
     </div>
  </>
}

export async function getServerSideProps(context) {
  return {
    props: {
       data: [], //tabs' data you fetched from the API
    }, 
  }
}

export default Tab

You can use shallow routing in next/route or next/link

Note that, in the below example, I'm using next/link for the demonstration. Without your tab data, I'd assume you have an array of tabs in data

import { useEffect } from 'react'
import Link from 'next/link'

//the path is `/tab/:tabId`
function Tab({ data }) {
  const [tabData, setTabData] = useState(data[0]) //first tab data as default for example

  useEffect(() => {
    setTabData(data[tabId])
  }, [router.query.tabId])

  return <>
     <Link href="/tab/0" shallow />
     <Link href="/tab/1" shallow />
     <div>
        {tabData}
     </div>
  </>
}

export async function getServerSideProps(context) {
  return {
    props: {
       data: [], //tabs' data you fetched from the API
    }, 
  }
}

export default Tab
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文