【问题标题】:NextJS Dynamic Routing, re-render specific Child ComponentsNextJS 动态路由,重新渲染特定子组件
【发布时间】: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 的

&lt;ChildComponent2 props={propsValue}&gt;

我使用动态路由,有这个链接:

<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


【解决方案1】:

当 props 参数更改时,组件会使用更改后的 props 进行渲染。

现在,由于 MainComponent 正在使用children,我们无法阻止它在没有昂贵的计算的情况下重新渲染,这无论如何都是开销。

但是,我们可以通过将 ChildComponent1 实现为 PureComponent 之类的方式来防止重新渲染

class ChildComponent1 extends React.PureComponent {}

如果你的 ChildComponent1 是一个函数式组件,你可以使用 React.memo 来防止在组件没有任何改变的情况下重新渲染

const ChildComponent1 = React.memo((props) => {
    // logic here
})

【讨论】:

  • 不,我的问题是如何在主组件内显示带有 url: /posts/${dynamic-pageId} 的 ChildComponent2?我想具体说明 NextJs 动态路由。
  • 您将在 MainComponent 右侧渲染 {props.children}。或者您是否只需要在 url 匹配时显示它。你也在用路由器吗?
  • 我只想用那个 url 做动态路由。我已将文件作为 [id].js 文件用于动态文件生成。在 [id].js 文件 getInitialProps() 方法中,我尝试使用 query.id 来获取 url 参数。通过该查询,我点击了 api 并获取数据。但是该数据应该传递给 mainComponent 并仅重新渲染第二个子组件。我们如何在 NextJs 中实现这一点?
猜你喜欢
  • 1970-01-01
  • 2021-09-30
  • 2021-01-11
  • 1970-01-01
  • 2016-02-24
  • 2019-03-02
  • 2022-06-12
  • 1970-01-01
  • 2019-11-26
相关资源
最近更新 更多