反应路由器参数
来自菜鸟教程
React Router 允许从 URL 中读取信息作为参数。
创建参数化路由
这只是 Route 的 path 属性的问题; 任何以冒号开头的段都将被视为参数:
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/" component={HomePage}/>
{/* Parameters are defined by placing a colon before a word. */}
{/* In this case, `username` is a parameter. */}
{/* Parameters will be passed to the component. */}
<Route path="/Users/:username" component={UserPage}/>
</div>
</BrowserRouter>
);
}
}
当 URL 与路径匹配时(例如:'/Users/Kevin'),将呈现该路由。
使用参数
当然,除非您可以访问参数,否则它并没有多大意义。 因此,React Router 将它们作为属性传递:
// Data from `Route` will be passed as a prop called `match`.
function UserPage({ match }) {
return (
<div>
{/* The URL is passed as `match.url`. */}
{/* `match.url` and `match.path` will be defined whether or not the path is parameterized. */}
<div>{`The URL is "${match.url}"!`}</div>
{/* The path (the one you gave `Route`) is passed as `match.path`. */}
<div>{`It matched the path "${match.path}"!`}</div>
{/* The parameters are passed as `match.params`. */}
<div>{`The parameter is "${match.params.username}"!`}</div>
</div>
);
}
match.params 将填充来自 URL 的值(即 对于 '/Users/Kevin',username 将是 'Kevin')。
参数可以在路径的任何部分,而不仅仅是在末尾; 例如,如果你想添加一个关于用户朋友的页面,你可以在 /Users/:username/Friends 处创建一个路由。