【问题标题】:Why the react route not working in nextjs?为什么反应路线在 nextjs 中不起作用?
【发布时间】:2021-11-16 09:26:27
【问题描述】:

pages/index.js 的内容如下:

import { BrowserRouter as Router,History, Switch, Route } from 'react-router-dom';
import TestSocket from '../components/testSocket/TestSocket';
export default function Index(){
    return(
        <Router>
          <Switch>
             <Route exact path='/a' component={TestSocket}/>
          </Switch>
       </Router>
   )
}

当我访问页面http://localhost:3000/a时,浏览显示

404 This page could not be found.

这个page 提出了同样的问题,但是,它没有明确说明如何解决这个问题。

您能帮忙详细说明一下解决方案吗?

【问题讨论】:

  • 请先阅读nextjs路由系统。 nextjs.org/docs/routing/introduction
  • 你的意思是我需要为 /components/testSocket/TestSocket.js 创建一个符号(即 /pages/a.js)目标吗?
  • 没错。 Next.js 有一个基于文件系统的路由。

标签: reactjs next.js


【解决方案1】:

因为Next.js 中的routingReact.js. 中的完全不同 在Next.js 中的第一个最大区别是缺少react-router-dom 及其功能(BrowserRouter、History、Switch、Route)

Next.js 有一个基于页面概念的router 文件系统。

当一个文件被添加到 pages 目录时,它会自动 可作为路线使用。

pages 目录中的文件可以用来定义最常见的 模式。

在这里,您可以找到解决问题的最佳来源,并帮助您从 React.js 路由器迁移到 Next.js 路由。 Migrating from React Router

【讨论】:

  • 您的意思是我无法将路径/a 映射到TestSocket 组件?
  • @TheKNVB 这意味着您在 react.js 中所做的方式在 next.js 中不起作用,请耐心阅读我发送给您的源代码... ;-) 迁移过程非常解释好吧。
  • 祝你好运 ;-) 最好的问候!
  • 这些答案解决了你的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2021-09-21
  • 1970-01-01
相关资源
最近更新 更多