React Router 官网

Hooks

useHistory

使用这个 hook 可以访问用于导航的 history 记录

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useHistory } from 'react-router-dom';

function HomeButton() {
let history = useHistory();
handClick = () => {
history.push('/home');
}
return (
<button type='button' onClick={handClick}>
Go home
</button>
)
}

useLocation

这个 hook 返回一个 location 对象, 相当于当前的 URL; 你可以把它想像成当 URL 发生变化时 useState 返回了一个新的 location

例: 如果希望每次加载新页面时使用网路分析工具触发新的“页面浏览”的情况, 可以使用这个 hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, useLocation } from 'react-router-dom';

function usePageViews() {
let location = useLocation();
useEffect(() => {
ga.send(['pageview', location.pathname])
}, [location]);
}

function App() {
usePageViews();
return <Switch>...</Switch>;
}

ReactDOM.render(
<Router>
<App />
</Router>,
node
)

useParams

1
2
3
4
5
6
7
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, Route, useParams } from 'react-router-dom';

function BlogPost() {
let { slog } = useParams();
}

useRouteMatch

BrowserRouter

HashRouter

MemoryRouter

Prompt

Redirect

Route

Router

StaticRouter

Switch

history

location

match

matchPath

withRouter