【问题标题】:Routers in NextjsNextjs 中的路由器
【发布时间】:2020-06-03 01:52:51
【问题描述】:

我正在对使用 ReactJS+Typescript 构建的现有应用程序进行更改,并且我一直在将其与 Typescript 一起迁移到 NextJs。

如何更改路由器?我检查了 Nextjs 的文档,但我很困惑。

当前路由在我的 App.tsx 文件中。这是代码。我想进行更改,因为当时我单击 handleSave 时,我的博客文章没有得到保存。我认为问题在于路由。

    return (
      <div className="All-Routes">
        <Switch>
          <Route
            exact
            path="/"
            component={props => <Index {...props} posts={this.state.posts} />}
          />
          <Route
            path="/posts/:id"
            component={props => (
              <Data {...props} post={this.state.posts[props.match.params.id]} />
            )}
          />
          <Route
            exactpath="/new"
            component={props => <Saving {...props} onSave={this.handleSave} />}
          />
        </Switch>
        <LocationDisplay />
      </div>
    );
  }
}
export default App;

【问题讨论】:

  • Nextjs 路由有不同的处理路由的方式。 pages 文件夹中的每个文件都是一个路由。因此,不需要Switch 组件(可能来自react-router),在 Next 中没有“持有”它自己的路由的组件。这是有原因的,Next 提供了 SSR,如果路由是 Component 的一部分,它需要渲染它才能决定渲染哪个 Component。

标签: reactjs typescript debugging react-router next.js


【解决方案1】:

创建一个如下所示的 routes.js 文件:

const nextRoutes = require('next-routes')
const routes = (module.exports = nextRoutes())

routes.add('/', 'index')

并用 expressjs 编写一个 server.js 并在其中添加以下行:

const routes = require('./routes')
const handler = routes.getRequestHandler(app)
...
server.get('*', (req, res) => {
    handler(req, res, parsedUrl)
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2022-06-16
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多