React整理总结(六, 路由)

1.React-router

  • HashRouter | HistoryRouter两种不同的路由
// index.tsx
import { HistoryRouter } from 'react-router-dom';

export default const  = () => {
	return (<>
		<HistoryRouter>
			<App/>
		</HistoryRouter>
	</>)
}
  • Routes | Route路由映射关系;Link | NavLink路由跳转
//App.tsx
export default const App = () => {
	return (<>
		<div className="header">
			<Link to="/home">home</Link>
			<Link to="/about">about</Link>
		</div>
		<div className="content">
			<Routes>
				<Route path="/home" element={<Home/>}/>
				<Route path="/about" element={<About/>}/>
				<Route path="*" element={<NotFound/>}/>
			</Routes>
		</div>
		<div className="footer">
	</>)
}
  • Navigate出现即重定向

2. 路由嵌套

  • Route内部继续写Route; Outlet在显示的位置站位
<Route path="/home" element={<Home/>} >
	<Route path="/home/recommend" element={<HomeRecommend/>} />
</Route>
  • 手动跳转路由useNavigate | withRouter(Comp)
// 函数式组件
const navigate = useNavigate();
const goToPath = (path) => {
	navigate(path);
}
// 类组件
withRoute(comp);

3. 路由参数

  • 动态路由
// 配置
<Route path="/datasource/:did" element={<SourceDetail />}/>
// 跳转
navigate(`/datasource/${id}`);
// 获取参数
const {did} = useParams();

const {did} = this.props.params;
  • search传参
<Link to={`/datasource?did={id}`}>详情</Link>
// 获取参数
const location = useLocation();
const search = location.search; // ?did=111

const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("did")

4.路由懒加载

  • React.lazy(void => component)懒加载路由配置
    const Home = React.lazy(() => import(“…/Components/Home”));
  • Suspence包裹App
<Suspence fallback={<Loading />}>
	<App/>
</Suspence >

你可能感兴趣的:(React学习,react.js,前端,前端框架)