Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

reactjs - React Router v4 routes not working

I am relatively new to reacts and I'm trying to figure out how to get React router to work. I've got a super simple test app that looks like this:

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

import {BrowserRouter as Router, Route, Switch, IndexRoute, Link} from 'react-router-dom';

const Home = () => <h1><Link to= "/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const Test = () => (
  <Router>
    <Switch>
    <Route path ="/" component = {Home} />
    <Route path ="/about" component = {About} />
    </Switch>
  </Router>
)

ReactDOM.render(<Test />, document.getElementById('app'));

when I run the app the home component loads without any trouble, and when I click the "Click Me" link the url changes to localhost/about, however nothing happens. If I click refresh I get a "Cannot GET /about." Clearly I am doing something wrong but I haven't been able to figure out what. I am also using Webpack.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use an exact path for / otherwise it will also match /about.

<Route exact path="/" component={Home} />

As mentioned in the comments, for something this simple I would suggest using Create React App which will make sure your server code and your webpack settings are all correct. Once you use create-react-app you'll just need to use npm to install the react router v4 package, and then put your code above into the App.js file and it should work. There are some small changes to your code to get it to work with create-react-app as can be seen below:

// App.js
import React from 'react';

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

const Home = () => <h1><Link to="/about">Click Me</Link></h1>
const About = () => <h1>About Us</h1>

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </Switch>
  </Router>
)

export default App;

The quick start instructions from React Router V4 documentation will tell you pretty much the same as I just explained.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...