如何在不使用 props 的情况下将数据传递到 NextJS 中的动态页面?注意:尝试重用数据并避免网络调用并尝试了 React Context

问题描述 投票:0回答:1

我有一个 NextJS 项目,正在为项目创建报告。

项目详细信息页面中有一个指向动态报告的链接 - 该报告利用上一页中显示的项目详细信息。

文件:项目信息

<Link
            href={{ pathname: '/Report' }}
          >
            <span className="mt-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
              Create Report
            </span>
          </Link>

但是我无法在不使用道具的情况下传递数据,尝试了反应上下文,但它没有按预期工作。

我尝试使用反应上下文。

在组件中,创建了一个名为 Context.jsx 的文件,如 log Rocket 的示例所示,位于 https://blog.logrocket.com/react-context-api-deep-dive-examples/

文件:Context.jsx

import { createContext } from 'react';
export const ProjectInfoContext = createContext({});
export const ProjectInfoProvider = ProjectInfoContext.Provider;
export default ProjectInfoContext;

并在项目信息页面中的 fetch 调用后使用了提供程序

文件:projectInfo.jsx

import {ProjectInfoProvider} from 'components/Context';

export default ProjectInfoPage() {

const [project, setProject] = useState(null);

 useEffect(() => {
        // Fetch project details when the component mounts
        fetch(`/projects/get/${id}`)
            .then((res) => res.json())
            .then((data) => {
                setProject(data); // Update the project data state with the fetched data
            }
            )
            .catch((error) => {
                console.error('Error fetching data:', error);
            }
            );
           
    },[])

return (
<ProjectInfoProvider value={project}>
                Project Title: {project.title}
//Details displayed 
 <Link
            href={{ pathname: '/Report' }}
          >
            <span className="mt-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
              Create Report
            </span>
          </Link>
            </ProjectInfoProvider>
);

}

我尝试过以下操作 从 nextjs Link 组件传递数据并在 getStaticProps 中使用它,但在这种情况下,作者希望进行另一个网络调用,而我只是希望利用我从项目的网络调用中收到的数据信息页面,使用路由器根据 id 呈现信息。

next.js router next.js13
1个回答
0
投票

回答这个问题的具体代码将在一定程度上取决于您使用的 Next 版本,更重要的是您使用的是应用程序路由器还是页面路由器。

IMO,如果您只想将项目的 id 传递到呈现的页面,那么最简单的方法就是使用动态路由。 NextJS 动态路由文档(应用程序路由器)

假设您正在使用应用程序路由器:

1。使用路径

/app/Reports/[id]/page.tsx

创建一个文件

在此文件中,您将声明具有如下基本结构的组件

import React from 'react'

const page = ({ params }: { params: { id: string } }) => {
  const projectId = params.id

  return (
    <<YOUR CODE HERE>>
  )
}

export default page

2。从您需要的任何地方链接到此路线

您可以使用下一个

<Link>
组件和要链接到的项目 ID 来完成此操作,如下所示。

const projectId = <<YOUR_PROJECT_ID>>
.
.
.
<Link href={'/Reports/' + projectId}>
  Create Report
</Link>

通过这种方式,您可以访问报告的 id 并进行相应的渲染。

© www.soinside.com 2019 - 2024. All rights reserved.