Next js中的嵌套路由

reactjs React.js

阿飞

2020-03-23

我有一个简单的SPA,App和About组件如下所示。当我单击“关于”链接时,“关于”页面将显示在链接下方。问题是,当我单击“关于我”链接时,将加载“我”页面而不是关于页面。我真正想要的是在nextjs中嵌套路由。似乎一级路由正在加载中。但是我不知道如何将其添加到我的子组件中。

import App, { Container } from 'next/app'
import React from 'react'
import Link from 'next/link'
class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }
    return { pageProps }
  }
  render() {
    const { Component, pageProps } = this.props
    return <Container>
      <ul>
        <li><Link href="/news">News</Link></li>

        <li><Link href="/about">About</Link></li>
      </ul>
      <Component{...this.props} />
    </Container>
  }
}
export default MyApp


import React from 'react'
import Link from 'next/link'
import Router from 'next/router'
class About extends React.Component {
  render() {
    return (
      <div id="main">
        <li><Link href="/about/company">About company</Link></li>
        <li><Link href="/about/me">About me</Link></li>

      </div>

    )
  }
}
export default About

第2957篇《Next js中的嵌套路由》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
LEYLEY 2020.03.23

我终于找到了解决这个问题的方法。我根据建议使用布局组件的此问题更改了代码:https : //github.com/zeit/next.js/issues/4166

class About extends React.Component {
  render() {
    return (
      <div id="main">
        <li><Link href="/about/company">About company</Link></li>
        <li><Link href="/about/me">About me</Link></li>
        {this.props.child}
      </div>

    )
  }
}
export default About

那么我小时候要展示的内容应该是这样的:

const me = () => (
  <About>
    <div>
     About me
    </div>       
  </About>
  )

这样可以防止页面重新加载。但是,它仍会重新呈现整个页面。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android