【发布时间】:2020-08-16 20:41:18
【问题描述】:
我有 index.js 页面,位于
pages/posts/index.js
我可以使用链接呈现此页面:
<Link href={`/posts`} />
这是我的 index.js 页面:
function mainComponent({props}) {
<>
<MainComponent>
<ChildComponent1/>
<ChildComponent2 props={propsValue}/>
<MainComponent/>
</>
}
现在,通过 NextJs 的动态路由,我想使用查询参数并调用 api 来获取 propsValue 的
<ChildComponent2 props={propsValue}>
我使用动态路由,有这个链接:
<Link href={/posts/${dynamic-pageId}} />
我可以仅使用从 API 获得的值 propsValue 重新渲染 ChildComponent2 吗?
注意:我没有物理文件作为/pages/posts/${dynamic-pageId},我想使用那个/pages/ posts/index.js,因为我也必须在这个hirerachy中渲染:
<>
<MainComponent>
<ChildComponent1/>
<ChildComponent2 props={propsValue}/>
<MainComponent/>
可以在 NextJs 中实现吗?
【问题讨论】:
-
是否需要从主组件传递props?你可以有 posts/[dynamic-pageId].js 文件来渲染你的子组件,使用 getStaticProps,你可以获得特定的道具。
-
不,我必须在主组件中呈现该子组件。我已经创建了 posts/[dynamic-pageId].js 这个文件。但是在该文件中渲染什么?
-
您可以定义您的自定义服务器,以便
posts/[id]将路由到/posts/index.js文件,您可以在该文件中获取id作为查询参数。
标签: javascript reactjs next.js router dynamic-routing