React App不路由到链接

时间:2018-02-23 02:11:50

标签: javascript reactjs react-router react-router-v4

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

以下是从我的index.html调用的代码。当我点击“显示列表”链接时,网址从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
};

1 个答案:

答案 0 :(得分:0)

我稍微重构了你的代码,你不应该为单个页面渲染App组件,而是你的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,这很好。