reactjs - Nextjs 动态路由 - 如何将道具从父级传递给动态路由子级
问题描述
使用 next@latest 及其动态路由功能。我有
/pages/index.tsx
和/pages/department/[slug]/index.tsx
。第一个 index.tsxgetStaticProps
用于拉入一些数据。在开发期间,此数据是自动生成的对象数组。然后我通过索引组件中的 props.departments 渲染这些对象。
我正在显示部门列表,并希望将项目链接到单个页面:
{departments.map(dept => (
<Link
as={`/department/${dept.slug}`}
href="/department/[slug]"
>
...
</Link>
)}
似乎没有办法传递道具,因为没有明显的父/子连接。
我是否必须在 [slug]/index.tsx 中查询单个部门,我应该使用 react useContext,还是有更好的设计方法可以解决这个问题?
感谢您的任何指导。
解决方案
如果您选择使用上下文 API 在两个路由之间共享状态,/pages/index.tsx
并且/pages/department/[slug]/index.tsx
您必须将App
组件与上下文提供程序一起包装在_app.tsx
. 这将导致另一个问题,如果您还有另外三个不需要数据的路由,它们也将成为上下文提供者的子级,而不使用上下文中的值。
我建议在数据获取方法中查询数据,即getStaticPaths
,getStaticProps
如果使用静态生成并且getServerSideProps
为单个部门使用服务器端渲染。
这是一些伪代码的样子/pages/department[slug]/index.tsx
如果使用静态生成
export const getStaticPaths: GetStaticPaths = async () => {
let paths: {params: { slug: string;}}[] = [];
// generate the paths for the pages you want to render
return {
paths,
fallback: false // false if you know all the slugs that you want to generate ahead of time
}
}
interface IProps {
// props for your page
}
export const getStaticProps: GetStaticProps<IProps> = async (context) => {
// get the slug
const slug = context.params?.slug;
// query the data based on slug
return {
props: {
// return the queried data as props
}
}
}
如果使用服务器端渲染
interface IProps {
// data you need as props
}
export const getServerSideProps: GetServerSideProps<IProps> = async (context) => {
// get the slug
const slug = context.params.slug
// query the data
return {
props: {
// return the queried data
}
}
}
PS-getStaticProps
将为getStaticPaths
构建时返回的每个路径调用一次。getServerSideProps
将根据请求调用,因此请根据需要选择要如何获取数据。
推荐阅读
- bash - 根据用户输入重复 bash 脚本
- r - 使用 R 包bayesplot 中的 mcmc_areas() 更改一些后验分布的颜色
- visual-studio-code - VSCode:在定义的文本之间切换
- arrays - 用 3 个参数减少调用,中间有一个奇怪的参数
- python - 将模块文件夹名而不是文件名添加到 Tortoise ORM config_file
- html - 如何使用 Bootstrap(我猜)让 iframe 填充剩余屏幕区域的宽度和高度?
- python - Kubernetes 集群中使用 Python 套接字的服务器-客户端连接
- c# - ASP.NET Core - IServiceProvider 何时处置?
- docker - 在 Container-Optimized OS 中保存持久性可执行文件的位置
- python - 计数符号更改