Router中包含了对路径改变的监听,并且会将相应的路径传递给子组件
BrowserRouter是history模式,HashRouter模式
使用两者作为最顶层组件包裹其他组件
Route用于路径的匹配,然后进行组件的渲染,
<Route path="/" render={() => <h1>Welcome!</h1>} />通常路径的跳转是使用Link组件,最终会被渲染成a元素,其中属性to代替a标题的href属性
NavLink是在Link基础之上增加了一些样式属性,例如组件被选中时,发生样式变化,则可以设置NavLink的一下属性:
- activeStyle:活跃时(匹配时)的样式
- activeClassName:活跃时添加的class
通过Route作为顶层组件包裹其他组件后,页面组件就可以接收到一些路由相关的东西,比如props.history
用于路由的重定向,当这个组件出现时,就会执行跳转到对应的to路径中
{name !== "tom" ? <Redirect to="/" /> : null}swich组件的作用适用于当匹配到第一个组件的时候,后面的组件就不应该继续匹配
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/profile" component={Profile} />
<Route path="/:userid" component={User} />
<Route component={NoMatch} />
</Switch>useHistory可以让组件内部直接访问history,无须通过props获取
const history = useHistory();
onClick={() => history.push("/")}const { name } = useParams();useLocation 会返回当前 URL的 location对象
例如将path在Route匹配时写成/detail/:id,那么 /detail/abc、/detail/123都可以匹配到该Route
props.match.params.xxx
/detail2?name=why&age=18
props.location.search