当我在浏览器中输入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键告诉SERVER为您服务页面http://localhost:8080/hello。您不希望这样,服务器在这里应该是被动的,除了主要index.html之外,不能为您提供任何其他页面。因此,相反,您希望服务器为您提供http://localhost:8080,并这样做,它将加载您的主要index.html和脚本,然后react接管,react-router检查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负责路由。 Here's more on Webpack-dev-server

然后在您的终端中运行npm run start:dev以启动开发服务器。

我希望所有这些都是有意义的,并且借助这些指南,您可以使代码正常工作。如果没有让我知道;)

注意:亚历克斯也有一个好点。 React Router v4渲染所有匹配的路由。因此,如果路径为http://localhost:8080/hello
//hallo都将匹配并呈现。如果只想渲染一个,请使用Alex提到的exact,或将路径包装在<Switch>组件中。

<Switch>
  <Route path="/" component={App}/>
  <Route path="/hello" component={Hello}/>
</Switch>


这是react-router docs所说的。


  渲染第一个孩子或与位置匹配的孩子


更新:
OP上载有问题的存储库后,已更正以下内容,以使路由正常运行。如果有人感兴趣,请the fixed project is on GitHub

使项目工作的要点:


使用react-router-dom代替react-router
告诉Express将所有传入流量路由到index.html app.get("/*", (req, res) => res.sendFile(__dirname + '/public/index.html'));
使用<Switch><Route>组件按照问题中的说明设置路由。 See code here

关于javascript - 为什么React-Router无法显示正确的组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51865349/

10-09 18:37
查看更多