特性变更
path:与当前页面对应的URL匹配。
element:新增,用于决定路由匹配时,渲染哪个组件。代替,v5的component和render。
<Outlet>Outlet>让嵌套路由更简单
useNavigate代替useHistory
移除了的activeClassName 和 activeStyle
钩子useRoutes代替react-router-config
https://reactrouter.com/docs/en/v6/upgrading/v5
{/*}/>*/}
}/>
}/>
}/>
}/>
index用于嵌套路由,仅匹配父路径时,设置渲染的组件。
解决当嵌套路由有多个子路由但本身无法确认默认渲染哪个子路由的时候,可以增加index属性来指定默认路由。index路由和其他路由不同的地方是它没有path属性,他和父路由共享同一个路径。
(1) 官方推荐方案 1: 使用 Navigate 组件替代
{/* }/> */}
}/>
}/>
}/>
}/>
(2) 官方推荐方案 2: 自定义 Redirect 组件
}/>
function Redirect({to}){
const navigate =useNavigate()
useEffect(() => {
navigate(to,{replace:true})
})
return null
}
(3) 404如何实现?
}/>
}/>
}>
{/* }/> */}
}/>
}/>
}/>
Film组件
isActive ? "kerwinactive" : ""} >正在热映
isActive ? "kerwinactive" : ""}>即将上映
//url传参
const navigate = useNavigate()
navigate(`/detail?id=${id}`)
//获取url参数
import { useSearchParams } from 'react-router-dom'
const [searchParams, setSearchParams] = useSearchParams()
// 获取参数
searchParams.get('id')
// 判断参数是否存在
searchParams.has('id')
// 同时页面内也可以用set方法来改变路由
setSearchParams({"id":2})
//跳转页面,路由传参
navigate(`/detail/${id}`)
//配置动态路由
}/>
//获取动态路由参数
const {id} = useParams()
}/>
function AuthComponent({children}){
return localStorage.getItem("token")?
children:
}
import {HashRouter} from 'react-router-dom'
import {BrowserRouter} from 'react-router-dom'
/*
* @作者: kerwin
* @公众号: 大前端私房菜
*/
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let push = useNavigate();
let params = useParams();
return (
);
}
return ComponentWithRouterProp;
}
export default withRouter
const LazyLoad = (path) => {
const Comp = React.lazy(() => import(`../views/${path}`))
return (
加载中...>}>
)
}
export default function MRouter() {
return (
{/* }/> */}
{/* }/> */}
}/>
{LazyLoad("Center")}
}/>
}/>
)
}
export default function MRouter() {
const element = useRoutes([
{path:"/film",element:LazyLoad("Film"),children:[
{
path:"",
element:
},
{
path:"nowplaying",
element:LazyLoad("film/Nowplaying")
},
{
path:"comingsoon",
element:LazyLoad("film/Comingsoon")
}
]},
{
path:"/cinema",element:LazyLoad("Cinema")
},
{
path:"/login",element:LazyLoad("Login")
},
{
path:"/center",element:
{LazyLoad("Center")}
},
{
path:"/detail/:id",element:LazyLoad("Detail")
},
{
path:"/",element:
},
{
path:"*",element:LazyLoad("NotFound")
},
])
return element
}