【React-Router6】Hooks 汇总
React-Router 6 引入了全新的hooks API,以下是一些常用的React-Router 6 hooks以及它们的简单示例:
- useRoutes:根据定义的路由规则来渲染对应的组件。
import { useRoutes } from 'react-router-dom';
function App() {
let element = useRoutes([
{ path: '/home', element: <Home /> },
{ path: '/about', element: <About /> },
// 嵌套子路由
{ path: '/dashboard', element: <Dashboard />,
children: [
{ path: 'profile', element: <Profile /> },
{ path: 'settings', element: <Settings /> },
]
}
]);
return element;
}
- useLocation:获取当前的location对象。
import { useLocation } from 'react-router-dom';
function MyComponent() {
let location = useLocation();
return (
<div>You are now at {location.pathname}</div>
);
}
- useNavigate:用于程序性导航,可以返回到历史记录中的某个位置。
import { useNavigate } from 'react-router-dom';
function MyComponent() {
let navigate = useNavigate();
function handleNavigation() {
navigate('/home');
}
return (
<button onClick={handleNavigation}>Go to Home</button>
);
}
- useParams:获取URL参数。
import { useParams } from 'react-router-dom';
function MyComponent() {
let params = useParams();
return (
<div>User ID: {params.userId}</div>
);
}
- useMatch:检查当前URL是否匹配特定的路由模式。
import { useMatch } from 'react-router-dom';
function MyComponent() {
let match = useMatch('/home');
return (
<div>{match ? 'We are at the home page.' : 'Not at the home page.'}</div>
);
}
- useSearchParams:获取和设置URL的查询参数。
import { useSearchParams } from 'react-router-dom';
function MyComponent() {
let [searchParams, setSearchParams] = useSearchParams();
function handleSearchChange() {
setSearchParams({ search: 'react-router' });
}
return (
<button onClick={handleSearchChange}>Change Search Params</button>
);
}
这些hooks是React-Router 6中用于导航和路由的核心工具,它们简化了路由逻辑的组织和复用,提高了代码的可维护性和易读性。
评论已关闭