简体   繁体   中英

React App not routing to the link

I am new to React and having issues with router. I am just learning from this tutorial: https://medium.com/@thejasonfile/basic-intro-to-react-router-v4-a08ae1ba5c42

Below is the code that is being called from my index.html. When I click on the link 'Show the list', the url changes from localhost:8080 to localhost:8080/list but doesn't really change the context of the page. I am not sure what is going or what I am doing wrong here. Any ideas?

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
};

I refactored your code a bit, you should not render the App component for a single page rather your app component should have all the routes like how I made it below. Then as needed add Link throughout your components when you need to navigate and then add the routes in App respectively.

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 is usually root looks like you changed it to app which is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM