如何在本地主机:3000 / home而不是本地主机:3000上加载React应用程序?

时间:2018-10-26 13:46:21

标签: reactjs

如上所述,如何在开始时在localhost:3000 / home而不是localhost:3000加载我的应用程序。我通常只是在控制台中运行npm start。

3 个答案:

答案 0 :(得分:3)

您可以使用react-router-dom

这是一个有效的示例:https://stackblitz.com/edit/react-router-starter-w1in3e?file=index.js

请参见以下示例:

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom';

import About from './components/About';
import Home from './components/Home';
import Topics from './components/Topics';

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
      </ul>

      <hr />

      <Route exact path="/" component={() => (<Redirect to='/home' />)} />
      <Route exact path="/home" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

render(<BasicExample />, document.getElementById('root'));

答案 1 :(得分:0)

将您的package.json更改为

"start": "npm run build",
"build": "webpack -d && cp src/home.html dist/home.html && webpack-dev-server --content-base src/ --inline --hot --history-api-fallback",
"build:prod": "webpack -p && cp src/home.html dist/home.html"

答案 2 :(得分:0)

如果您使用的是React Router,还可以在React Router中指定基本名称。

 <Router basename="home">
      <Route path="/" component={App} />
    </Router>

有关基本名称的更多信息: https://reacttraining.com/react-router/web/api/BrowserRouter

@Akshay Milmile的建议很好