记录一下学习 React 全家桶中的 react-router
examples
路由参数
通过 hooks 获取
1 | let { id } = useParams(); |
Route
route props
所有渲染方式会传递以下三种 props
- match
- location
- history
会在 props 接受这三个 props
component
当你使用 component 时,router 使用 React.CreateElement 根据传递的 component 创建一个新的 React element 。这意味着如果你提供了一个内联的函数给 component 属性,你会在每次 render 的时候都创建这个组件,这会导致旧组件的 unmount 和 新组建的 mount
其背后的原理在于,react 在比较组件状态以便决定如何更新 dom 节点时,首先要比较组件的 type 和 key。在使用<Route component={() => (<Bar idx={this.state.idx}/>)}/>
时,由于调用了 React.createElement,组件的 type 不是 Bar 这个类,而是一个匿名函数。App 组件每次 render 时都生成一个新的匿名函数,导致生成的组件的 type 总是不相同,所以会产生重复的 unmounting 和 mounting。
render
允许方便的内联渲染,避免不必要的重新挂载。当路由匹配的时候,这个函数会被调用。函数可以访问所有的 props。
<Route component>
优先级高于 <Route render>
children
有时你需要渲染渲染子组件,不管路由是否匹配。这种情况下,可以使用 children 。
exact
当为 true,进行精确匹配。
strict
当为 true,路径中的 slash 也必须精确匹配。
sensitive
当为 true,大小写敏感。
history 是可变对象
1 | class Comp extends React.Component { |
Link
to
可以是一个路径字符串,也可以是一个对象
1 | { |
也可以是一个函数,传递当前的 location,返回一个字符串或者对象
replace
当为 true,替换历史栈中的当前记录,而不是添加一条记录
NavLink
activeClassName
默认的类名是 active,这将会被连接到 className 属性后
link-exact
当为 true,activeClassName 和 activeStyle 只会在精确匹配时生效
link-strict
结合 Route 的 strict,会跳转到严格匹配的路由
isActive
1 | <NavLink |