1.安装
npm i react-router-dom@5.0 -S
2.组件
- BrowserRouter 浏览器路由
HashRouter 哈希路由- NavLink 导航链接
- exact 精确匹配
- to 链接地址
- class=“active”匹配状态- Route 路由容器
- exact 精确匹配
- pathname和配置path完全匹配)
- path 路由地址
- component 组件<Redirect>
重定向
- to 去哪
- from 从哪<Switch>
匹配一个路由<Prompt>
路由离开时调用弹窗
- when:当条件为真
- message:弹出的文本内容<Link>
跳转
to="/login" to={{ pathname:"/login/, search:"name:"mumu",age:18", hash:{#good"}, state:{}, }}
参数props里面的location一致的- 404
- Switch包裹(一次匹配一个)
- path=“*”
- 配置放在最后面
3. 路由props
-
match 匹配的路由
params 路由的参数
isExact 是否精确匹配
path 路径
url 地址 -
history历史记录
push 跳转
replace 替换历史记录
goBack 返回
goForward 前进
go 跳转历史记录
listen 监听
location
length 长度 -
location地址栏
hash 哈希值
pathname 地址名称
search 查询信息
state 跳转传入参数 -
只有Route对应的component才有这自动注入的三个参数
4. reactHook 在函数组件里面模拟生命周期和状态state
1. useState使用状态
const [state, setstate] = useState(initialState)
2. useEffect模拟生命周期
第一个参数是回调函数,模拟组件已经挂载完毕
第一个参数的返回值,模拟组件将要卸载
第二个参数:依赖数据
3. useRef 使用DOM引用
const inpRef=useRef();
<input type="text" ref={inpRef} />
inpRef.current.value
4. useCallback使用回调缓存执行一个函数
5. useMemo使用缓存,返回一个函数
6. useLayouEffect视图发生变化
7. useReducer 集中数据管理器(模拟reduce)
5. 常见的react-router-dom组件
import {
HashRouter as Router, //哈希路由
BrowserRouter as Router ,//浏览历史记录路由
Router,//路由
NavLink,//导航链接
Redirect,//重定向
Switch, //切换
Prompt, //弹出
Link //连接
} from 'react-router-dom'
6. react生命周期
1.挂载
componentDidMount 组件已经挂载(cdm)
constructor 构造函数
static getDerivedStateFromProps(props, state)监听
render 渲染
2.更新
shouldComponentUpdate(nextProps, nextState) 组件是否更新(scu)
static getDerivedStateFromProps(props, state) 监听props更新
render 渲染函数
getSnapshotBeforeUpdate(prevProps, prevState) 更新获取快照返回的数 据是cdu的第三个参数(gsbu)
componentDidUpdate(prevProps, prevState) 组件已经更新(cdu)
3.卸载
componentWillUnmount 组件将要卸载(cwun)