React App 没有路由到 link

React App not routing to the link

我是 React 新手,遇到路由器问题。我刚刚从本教程中学习:https://medium.com/@thejasonfile/basic-intro-to-react-router-v4-a08ae1ba5c42

下面是从我的 index.html 调用的代码。当我单击 link 'Show the list' 时,url 从 localhost:8080 变为 localhost:8080/list 但并没有真正改变页面的上下文。我不确定发生了什么或我在这里做错了什么。有什么想法吗?

Scripts.js

import React from 'react';
import ReactDOM from 'react-dom';

import {Title, App} from './Components/App';
import { BrowserRouter as Router, Route } from 'react-router-dom';

ReactDOM.render(
    <Router>
      <div>
        <Route exact path="/" component={Title} />
        <Route path="/list" component={App} />
      </div>
  </Router>
    , document.getElementById('app'));

App.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
const Title = () => {
  return (
      <div className="title">
        <h1>React Router demo</h1>
        <Link to="/list">
          <button>Show the List</button>
          </Link>
          </div>
      )};
const List = () => {
  return (
    <div className="nav">
      <ul>
        <li>list item</li><li>list item</li></ul><Link to="/"><button>Back Home</button></Link></div>)
}
module.exports = {
  Title,
  List
};

我稍微重构了你的代码,你不应该为单个页面呈现 App 组件,而你的应用程序组件应该像我在下面制作的那样具有所有路由。然后根据需要在需要导航时在整个组件中添加 Link,然后分别在 App 中添加路由。

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

class App extends Component {
  constructor() {
    super();
  }

  render() {
    return (
    <Router>
      <div>
        <Route exact path='/home' render={()=> <Title />} > </Route>
        <Route exact path='/list' render={() => <List />} > </Route>
      </div>
    </Router>
    );
  }
}

const Title = () => {
  return (
      <div className="title">
        <h1>React Router demo</h1>
        <Link to="/list">
          <button>Show the List</button>
          </Link>
          </div>
      )};
const List = () => {
  return (
    <div className="nav">
      <ul>
        <li>list item</li><li>list item</li></ul><Link to='/home'><button>Back Home</button></Link></div>)
}
render(<App />, document.getElementById('app'));

document.getElementById 通常是 root 看起来你把它改成了 app 没问题。