yarn add react-router-dom
<Route>
中的 match.params (动态参数)<Route>
import { useHistory } from "react-router-dom";
function JumpPage() {
let history = useHistory();
function handleClick() {
history.push("/跳转位置");
}
return (
<button type="button" onClick={handleClick}>
Go back
</button>
);
}
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
useLocation
} from "react-router-dom";
function usePageViews() {
let location = useLocation();
React.useEffect(() => {
ga.send(["pageview", location.pathname]);
}, [location]);
}
function App() {
usePageViews();
return <Switch>...</Switch>;
}
ReactDOM.render(
<Router>
<App />
</Router>,
node
);
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route,
useParams
} from "react-router-dom";
function BlogPost() {
let { slug } = useParams();
return <div>Now showing post {slug}</div>;
}
ReactDOM.render(
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/blog/:slug">
<BlogPost />
</Route>
</Switch>
</Router>,
node
);
useRouteMatch 尝试以与<Route>
相同的方式匹配当前URL。
import { useRouteMatch } from "react-router-dom";
function BlogPost() {
let match = useRouteMatch("url");
// 匹配你想要匹配的url
return <div />;
}
// ------等比于------
import { Route } from "react-router-dom";
function BlogPost() {
return (
<Route
path="url"
render={({ match }) => {
// 匹配你想要匹配的url
return <div />;
}}
/>
);
}
useRouteMatch 钩子也可以:
<Route>
const match = useRouteMatch({
path: "url",
strict: true,
sensitive: true
});