【问题标题】:React-router v5.2 routes aren't working, only home page is displayedReact-router v5.2 路由不工作,只显示主页
【发布时间】:2020-11-18 20:29:01
【问题描述】:

我使用的是 5.2 版路由器,我正在尝试在文件 app.js 中创建路由。 我的路线如下所示:

import React from 'react';
import { render } from 'react-dom'; // if you use just render()
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    ReactDOM.render(
      <Router>
        <div>
          <Switch>
            {/* Using the `component` prop */}
            <Route exact path="/" component={Homepage} />
            <Route path="/display-item" component={DisplayProduct} />
            <Route path="/category/:id" component={DisplayCategory} />
            <Route path="/product/:id" component={OneProduct} />
            <Route path="/checkout" component={CheckOut} />
            <Route path="/orderPlaced" component={OrderPlaced} />
          </Switch>
        </div>
      </Router>,
      document.getElementById('crud-app'),
    );

问题是只有路由/ 有效。所以只显示主页。

当我尝试访问 http://localhost:8000/#/display-item 时,什么也没有发生。所以我还在主页上,控制台中没有任何警告或错误。

如果我转到http://localhost:8000/display-item,则会收到错误GET http://localhost:8000/display-item 404 (Not Found)

请问有人遇到过类似的问题吗?如何解决?

谢谢!

更新:

【问题讨论】:

  • 你是如何导入Router的?
  • 赞这个import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  • 一切看起来都正确。 localhost:8000/display-item 应该将您带到 DisplayProduct 组件,并且您没有使用 react 路由器收到 404 错误
  • 在 5.2 版之前,我使用了 3.2.6 版和 hashHistory,一切正常。现在,当我升级到 5.2 版并更改路线时,它无法正常工作。我附上了有问题的图片,所以你可以看到
  • 你在使用 Laravel 吗?看起来像是后端的路由问题。

标签: reactjs


【解决方案1】:

将 home 路由作为 switch 中的最后一条语句,然后它将起作用。在您的代码中,每条路径都与“/”匹配,因此每次它都会转到主路径。如果将它放在最后,那么它将搜索确切路径。

【讨论】:

    【解决方案2】:

    问题出在后端 Laravel,除了 react 中的路由,你应该在 web.php 文件中定义路由

    Route::view('/', 'welcome');
    Route::view('/display-item', 'welcome');
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2021-12-28
      • 2022-08-02
      • 2022-03-23
      • 2021-04-08
      • 2019-06-15
      • 1970-01-01
      • 2019-10-20
      • 2018-12-18
      相关资源
      最近更新 更多