react-router-domV6版本改版踩坑記錄
1.父組件注冊路由
v5版本:
import { Route } from 'react-router-dom' <Route path="/about" component={About} /> <Route path="/home" component={Home} />
v6版本:
import { Route } from 'react-router-dom' <Route path="about" element={<About />} /> <Route path="home" element={<Home />} />
2.NavLink點擊高亮顯示
v5版本:
import { NavLink } from 'react-router-dom' <NavLink activeClassName="highlight" className="about" to="/about" >About</NavLink>
v6版本:
以下二者選一即可,一定要注意 (isActive ? " highlight") highlight前面的空格?。?! // 官方寫法 <NavLink className={({ isActive }) => "about" + (isActive ? " highlight" : "")} to="about">About</NavLink> // ES6 模版字符串寫法 <NavLink className={({ isActive }) => `about ${isActive ? "highlight" : ""}`} to="about">About</NavLink>
3.Switch(單一匹配)更換為Routes
import { Routes,Route } from 'react-router-dom' <Routes> <Route path="about" element={<About />} /> <Route path="home" element={<Home />} /> </Routes>
4.Redirect重定向
v5版本:
import { Redirect }from 'react-router-dom' <Routes> <Route path="/about" element={<About />} /> <Route path="/home" element={<Home />} /> // 寫在這里 <Redirect to="/about" /> </Routes>
v6版本:
import { Navigate }from 'react-router-dom' <Routes> <Route path="about/*" element={<About />} /> <Route path="home/*" element={<Home />} /> // 寫在這里 <Route path="/*" element={<Navigate to="/about" />} /> </Routes>
5.嵌套路由
v5版本:
// 父組件 <Route path="home/" element={<Home />} /> // 路由鏈接 <NavLink className="about" to="/home/news" >News</NavLink> // 注冊路由和重定向 <Switch> <NavLink className="news" to="/home/news" >News</NavLink> <NavLink className="message" to="/home/message" >Message</NavLink> <Redirect to="/home/news" /> </Switch>
v6版本:
// 父組件 <Route path="home/*" element={<Home />}> // 路由鏈接 <NavLink className="news" to="news" >News</NavLink> <NavLink className="message" to="news" >News</NavLink> // 注冊路由和重定向 <Routes> <Route path="news" element={<News />} /> <Route path="message" element={<Message />} /> <Route path="/" element={<Navigate to="news" />} /> </Routes>
6.params參數(shù)傳遞
v5版本:
//路由鏈接(攜帶參數(shù)): <Link to='/demo/test/tom/18'}>詳情</Link> //或 <Link to={{ pathname:'/demo/test/tom/18' }}>詳情</Link> //注冊路由(聲明接收): <Route path="/demo/test/:name/:age" component={Test}/> //接收參數(shù): this.props.match.params
v6版本:
//路由鏈接(攜帶參數(shù)): <Link to={{ pathname:`/b/child1/${id}/${title}` }}>Child1</Link> //或 <Link to={`/b/child1/${id}/${title}`}>Child1</Link> //注冊路由(聲明接收): <Route path="/b/child1/:id/:title" element={<Test/ >} /> //接收參數(shù):接收參數(shù)的組件一定要是函數(shù)式聲明的(class不可以)?。?! import { useParams } from "react-router-dom"; const params = useParams(); //params參數(shù) => {id: "01", title: "消息1"}
7.search參數(shù)
v5版本:
//路由鏈接(攜帶參數(shù)): <Link to='/demo/test?name=tom&age=18'}>詳情</Link> //注冊路由(無需聲明,正常注冊即可): <Route path="/demo/test" component={Test}/> //接收參數(shù): this.props.location.search //備注:獲取到的search是urlencoded編碼字符串(例如: ?id=10&name=zhangsan),需要借助query-string解析參數(shù)成對象
v6版本:
//路由鏈接(攜帶參數(shù)): <Link className="nav" to={`/b/child2?age=20&name=zhangsan`}>Child2</Link> //注冊路由(無需聲明,正常注冊即可): <Route path="/b/child2" component={Test}/> //接收參數(shù)方法1:接收參數(shù)的組件一定要是函數(shù)式聲明的(class不可以)?。?! import { useLocation } from "react-router-dom"; import { qs } from "url-parse"; const { search } = useLocation(); const searchs = qs.parse(search) //search參數(shù) => {age: "20", name: "zhangsan"} //接收參數(shù)方法2:接收參數(shù)的組件一定要是函數(shù)式聲明的(class不可以)!??! import { useSearchParams } from "react-router-dom"; const [searchParams, setSearchParams] = useSearchParams(); // console.log( searchParams.get("id")); // 12 //備注:獲取到的search是urlencoded編碼字符串(例如: ?age=20&name=zhangsan),需要借助 url-parse 里面的 qs.parse 解析參數(shù)成對象
8.state參數(shù)
v5版本:
//路由鏈接(攜帶參數(shù)): <Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>詳情</Link> //注冊路由(無需聲明,正常注冊即可): <Route path="/demo/test" component={Test}/> //接收參數(shù): this.props.location.state //備注:刷新也可以保留住參數(shù)
v6版本:
//通過Link的state屬性傳遞參數(shù) <Link className="nav" to={`/b/child2`} state={{ id: 999, name: "i love merlin" }} > Child2 </Link> //注冊路由(無需聲明,正常注冊即可): <Route path="/b/child2" component={Test}/> //接收參數(shù):接收參數(shù)的組件一定要是函數(shù)式聲明的(class不可以)?。?! import { useLocation } from "react-router-dom"; const { state } = useLocation(); const { xx, xx } = state || {} //state參數(shù) => {id: 999, name: "我是梅琳"} //備注:刷新也可以保留住參數(shù)
9.編程式路由跳轉(zhuǎn)
v5版本
v5版本:push跳轉(zhuǎn)攜帶params參數(shù)
props.history.push(`/b/child1/${id}/${title}`)
v5版本:push跳轉(zhuǎn)攜帶search參數(shù)
props.history.push(`/b/child1?id=${id}&title=${title}`);
v5版本:push跳轉(zhuǎn)攜帶state參數(shù)
props.history.push(`/b/child1`, { id, title });
v5版本:前進(jìn)
this.props.history.goForward();
v5版本:后退
this.props.history.goBack();
v5版本:前進(jìn)或回退 ( go )
this.props.history.go(-2); //回退到前2條的路由
v5版本:replace跳轉(zhuǎn)攜帶params參數(shù)
this.props.history.replace(`/home/message/detail/${id}/${title}`)
v5版本:replace跳轉(zhuǎn)攜帶search參數(shù)
this.props.history.replace(`/home/message/detail?id=${id}&title=${title}`)
v5版本:replace跳轉(zhuǎn)攜帶state參數(shù)
this.props.history.replace(`/home/message/detail`, { id, title });
v5版本:在一般組件中使用編程式路由導(dǎo)航 (非路由組件)
import {withRouter} from 'react-router-dom' class Header extends Component { // withRouter(Header)后,就可以在一般組件內(nèi)部使用 this.props.history //... } export default withRouter(Header)
v6版本
v6版本:
// v6版本編程導(dǎo)航使用 useNavigate import { useNavigate } from "react-router-dom"; export default function A() { const navigate = useNavigate(); //... }
v6版本:push跳轉(zhuǎn)攜帶params參數(shù)
navigate(`/b/child1/${id}/${title}`);
v6版本:push跳轉(zhuǎn)攜帶search參數(shù)
navigate(`/b/child2?id=${id}&title=${title}`);
v6版本:push跳轉(zhuǎn)攜帶state參數(shù)
navigate("/b/child2", { state: { id, title }});
v6版本:前進(jìn)
<button onClick={() => navigate(1)}>Go Forword</button>
v6版本:后退
<button onClick={() => navigate(-1)}>Go back</button>
v6版本:前進(jìn)或后退幾步
<button onClick={() => navigate(2)}>Go</button>
v6版本:replace跳轉(zhuǎn)攜帶params參數(shù)
navigate(`/b/child1/${id}/${title}`,{replace: true});
v6版本:replace跳轉(zhuǎn)攜帶search參數(shù)
navigate(`/b/child2?id=${id}&title=${title}`,{replace: true});
v6版本:replace跳轉(zhuǎn)攜帶state參數(shù)
navigate("/b/child2", { state: { id, title },replace: true});
10.函數(shù)組件使用生命周期需要用 useEffect
import React, { useEffect } from 'react' import { useNavigate } from 'react-router-dom' // 這里的作用是 componentDidMount export default function News() { const navigate = useNavigate() useEffect(() => { setTimeout(() => { navigate("/home/message") }, 2000) }) return ( <ul> <li>news001</li> <li>news002</li> <li>news003</li> </ul> ) }
11.withRouter(v6版本棄用)
直接使用 useNavigate 即可
12.class組件沒有this.props.history問題
// 我是這樣解決的:父組件App用函數(shù)式組件并引入 useNavigate 然后傳給子組件使用 // 父組件 import React from 'react' import { Routes, Route, useNavigate } from 'react-router-dom' export default function App() { const navigate = useNavigate() return ( <Routes> <Route path="/login" element={<Login navigate={navigate} />}> <Route path="/" elment={<Admin />}> </Routes> ) } // 子組件 export default class Login extends Component { // 定義跳轉(zhuǎn)的方法 jump = () => { this.props.navigate('/') } render() { return ( <button onClick={this.jump}>點擊跳轉(zhuǎn)</button> ) } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React報錯之Object?is?possibly?null的問題及解決方法
這篇文章主要介紹了React報錯之Object?is?possibly?null的問題,造成 "Object is possibly null"的錯誤是因為useRef()鉤子可以傳遞一個初始值作為參數(shù),而我們傳遞null作為初始值,本文給大家分享詳細(xì)解決方法,需要的朋友可以參考下2022-07-07React?SSR架構(gòu)Stream?Rendering與Suspense?for?Data?Fetching
這篇文章主要為大家介紹了React?SSR架構(gòu)Stream?Rendering與Suspense?for?Data?Fetching解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03