首页 > 解决方案 > Nextjs 中的路由器

问题描述

我正在对使用 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;

标签: reactjstypescriptdebuggingreact-routernext.js

解决方案


创建一个如下所示的 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)
  })

推荐阅读