首页 > 代码库 > React Route

React Route

 

  All the work we’ve done so far has either been inindex.js or Detail.js, but now we’re going to add a third file called List.js that will render a home page for our app. From there, users will be able to select a GitHub repository, and doing so will show Detail.js as before.

 So, we’ll go from having just one page listing all the React commits, forks and pulls on GitHub, to having a homepage first where users can select React, React Native, Jest, or other Facebook projects of our choosing. This involves a fairly big change, so we’re going to do this in two parts: first implement React Router in a way that preserves the exact behavior we have right now, then second add the new home page.

If you were wondering, React Router is a component that loads different pages depending on the URL your user asked for. So if the user goes tohttp://localhost:8080/helloit would serve one page, and http://localhost:8080/world would serve a different page.

Well, that’s not strictly true. To avoid having to add a server configuration, the pages React Router serves up will all start with/#/, e.g. http://localhost:8080/#/hello. This means thatindex.htmlwill automaticallybeusedtorenderallpages,whichinturnmeansthatReactRouterwillbeabletoload the right page.

src/index.js

 1   import React from ‘react‘;
 2   import ReactDOM from ‘react-dom‘;
 3   import { Router, Route, IndexRoute } from ‘react-router‘;
 4   import createHistory from ‘histroy/lib/createHistory‘;
 5  
 6  import Detail from ‘.page/Detail‘;
 7   
 8   ReactDOM.render(                                         
 9      <Router>                       //<Router history={creatHistory({ queryKey: false})}
10          <Route path="/" compent={ Detail } />     // onUpdate={() => window.sorollTo(0,0)}>//is right
11      </Router>,
12     document.getElementById(‘app‘)
13  );//is wrong

 /剖析Router,Route The first import brings three components, of which we’ll be using two immediately and the other shortly. Router is React Router itself, which takes a listofURLs and React components and puts the two together. Route is one individual URL mapping, e.g. the URL detail and our Detail component.  IndexRoute is used as a default route; we’ll get onto that soon.

React Route