- Add Routes to load “Users” and “Courses” on different pages (by
entering a URL, without Links)
使用BroswerRouter讲index.js的render内容包裹住
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
在app.js中设置两个Route标签,其component分别为users和courses
<Route path="/users" exact component={Users}/>
<Route path="/courses" component={Courses}/>
- Add a simple navigation with two links => One leading to “Users”,
one leading to “Courses”
在需要点击事件的地方加入Link,设置to参数,其地址与route的path一一对应
<nav>
<ul>
<li><NavLink to="/users">Users</NavLink></li>
<li><NavLink to="/courses">Courses</NavLink></li>
</ul>
</nav>
- Make the courses in “Courses” clickable by adding a link and load
the “Course” component in the place of “Courses” (without passing
any data for now)
在Courses中加入link,并且to为courses的url+其id
let obj={
pathname:this.props.match.url+'/'+course.id,
id:course.id,
title:course.title
}
<Link to={obj}>
<article
className="Course"
key={course.id}>{course.title}
</article>
</Link>
- Pass the course ID to the “Course” page and output it there
方法1:通过Route的通配符传入,由props.match.params.id得到
此方法会使得所有匹配的route都被render;
<Route
path={this.props.match.url+'/:id'}
component={Course}
/>
方法2:通过在link的to中传入obj,向下传入参数,在props.location中提取
<div>
<h1>{this.props.location.title}</h1>
<p>You selected the Course with ID: {this.props.location.id}</p>
</div>
- Pass the course title to the “Course” page - pass it as a param or
score bonus points by passing it as query params (you need to
manually parse them though!) - Load the “Course” component as a nested component of “Courses”
在Courses中设置course的地址——已做到
7. Add a 404 error page and render it for any unknown routes
**使用< Route component={} />即可设定4040返回 **
<Route component={ErrorPage}/>
- Redirect requests to /all-courses to /courses (=> Your “Courses”
page)
使用< Redirect /> 即可
<Redirect from='/all-course' to='/courses'/>