[ReactRouter] 基礎 Basic
💡 使用版本
^5.0.0
- react-router @ Github
- react-router @ Docs
React Router 的基本原理
基本用法
建立路由
keywords: BrowserRouter
, Route
, Switch
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(
<Provider store={store}>
<BrowserRouter>
<div>
// 原本的 router 只要能夠符合到前面的 path,該 component 就會被轉譯 // 透過
Switch,則是配對到符合的路由後,後面其他的就不在匹配(因此順序重要)
<Switch>
<Route path="/posts/new" component={PostsNew} />
<Route path="/" component={ComponentName} />
</Switch>
</div>
</BrowserRouter>
</Provider>
);
不用 <Switch>
的另一種方式是使用 exact
就好,只有在完全匹配到的時候才會顯示該路由的元件:
<Route path="/" component={ComponentName} exact />
建立連結
keywords: Link
, NavLink
使用 <Link></Link>
最後一樣會顯示為 <a></a>
標籤,差別在於 <Link>
會擋掉瀏覽器的一些預設行為,避免發出真正的 HTTP 請求:
import { Link } from 'react-router-dom';
<div className="text-right mb-4">
<Link className="btn btn-primary" href="#" role="button" to="/posts/new">
Add a Post
</Link>
</div>;
取得 Routes 中提供的屬性
當我們使用 <Router path="/foo" component={bar}>
後,這個 bar
component 中就會包含有由 React-Router 所提供的許多屬性可以使用,其中主 要包含:
match
location
history
staticContext
{
"match": {
"path": "/topics",
"url": "/topics",
"isExact": false,
"params": {}
},
"location": {
"pathname": "/topics/components",
"search": "",
"hash": "",
"key": "7m8jwd"
},
"history": {
"length": 36,
"action": "POP",
"location": {
"pathname": "/topics/components",
"search": "",
"hash": "",
"key": "7m8jwd"
}
}
}
如果某一元件並不是透過 <Route>
的 component
屬性進入,但是又希望能拿到這些相關資訊,則可以使用 withRouter
這個 HOC 來取得這些資訊:
const App = () => { ... };
export default withRouter(App);
/* 搭配 Redux */
// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))
// or
compose(
withRouter,
connect(...)
)(MyComponent)
其他
將參數傳到 component 中
在 <Route>
中可以使用 render
方法,其中可以透過 props
這個參數取得原本 Routes 所提供的屬性使用:
// 在 TestWidget 中會多 num 和 someProp 這兩個參數可以拿到
import TestWidget from '@/components/TestWidget';
<Route path="/abc" render={(props) => <TestWidget num="2" someProp={100} {...props} />} />;
Allow passing props to Route to be passed down to the component it renders @ React-Router Github How to pass props to components when you use Route attribute ? @ React-Router Github