[英]Why react-router does not display correct component?
當我在瀏覽器中輸入localhost:8080
,它會顯示 App.js 組件。 但是當我導航到localhost:8080/#/hello
它顯示相同的 App.js 組件而不是 hello.js。 localhost:8080/hello 顯示“無法獲取 localhost:8080/hello”。 我的代碼有什么問題? 我在我的應用程序中使用 webpack 和 babel。
//index.js
import React from 'react';
import ReactDOM, { render } from 'react-dom';
import { Provider } from 'react-redux';
import {store} from './public/store/store';
import App from './public/Components/App';
import Hello from './public/Components/hello';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom';
//import './index.css'
render(
<Provider store={store}>
<Router>
<div>
<Route path="/" component={App}/>
<Route path="/hello" component={Hello}/>
</div>
</Router>
</Provider>,
document.getElementById('root')
)
//App.js
import React from 'react';
export default class App extends React.Component {
render() {
return (
<div>
<h1>React Js.</h1>
</div>
);
}
}
//hello.js
import React from 'react';
export default class Hello extends React.Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
這里發生了一些事情,讓我嘗試解釋發生了什么問題以及如何修復它們。
http://localhost:8080/#/hello它顯示相同的 App.js 組件而不是 hello.js。
因為您使用的是BrowserRouter
而不是 HashRouter(舊版本,# 不起作用)。 瀏覽器只讀取 URL 的第一部分,即http://localhost:8080/
。 當您使用以下內容路由到頁面的某個部分時, #
類似。
<a href="#projects">Goto projects</a>
以上使用戶保持在同一頁面上,但滾動到<div id="projects"></div>
不要使用這個,如果你使用的是 React Router V4,它不是你想要的。
http://localhost:8080/hello顯示無法獲取http://localhost:8080/hello
您可能沒有運行支持前端路由的開發服務器。 如果你不這樣做,基本上發生的事情是通過按 Enter 你告訴服務器為你提供頁面http://localhost:8080/hello
。 你不想要這個,服務器在這里應該是被動的,除了你的主 index.html 之外,它不會為你提供任何其他頁面。 因此,相反,您希望服務器為您提供http://localhost:8080
並且這樣做,它會加載您的主要 index.html 和腳本,然后反應接管,反應路由器檢查 url,然后呈現給您/hello 帶有Hello
組件的路由。
為了實現這一點,請確保您已安裝webpack-dev-server
。 您可以通過在命令行中鍵入以下內容來執行此操作。 npm install webpack-dev-server --save-dev
然后將以下內容添加到您的 package.json
devServer: {
publicPath: '/',
historyApiFallback: true
}
// add the below line to the scripts section
"start:dev": "webpack-dev-server"
這基本上告訴開發服務器將所有請求重新路由到 index.html,因此 react-router 負責路由。 這里有更多關於 Webpack-dev-server 的內容。
然后在你的終端運行npm run start:dev
來啟動開發服務器。
我希望這一切都有意義,並且通過這些指南,您可以使您的代碼工作。 如果不讓我知道;)
注意: Alex 也有一個很好的觀點。 React Router v4 渲染所有匹配的路由。 因此,如果路徑是http://localhost:8080/hello
/
和/hallo
都匹配並將呈現。 如果您只想渲染一個,請使用 Alex 提到的exact
方法,或者將您的路線包裝在<Switch>
組件中。
<Switch>
<Route path="/" component={App}/>
<Route path="/hello" component={Hello}/>
</Switch>
這是react-router 文檔所說的。
渲染第一個孩子或匹配位置
更新:
在 OP 上傳了一個有問題的 repo 后,糾正了以下內容以使路由正常工作。 如果有人感興趣,固定項目在 GitHub 上。
使項目工作的要點:
react-router-dom
代替react-router
app.get("/*", (req, res) => res.sendFile(__dirname + '/public/index.html'));
<Switch>
和<Route>
組件來設置問題中描述的路由。 請參閱此處的代碼。嘗試使用exact
指令:
<Route exact path="/" component={App} />
請參閱 API 文檔:https ://reacttraining.com/react-router/web/api/Route/exact-bool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.