React路由器:可选参数
来自菜鸟教程
React Router 使 使用参数 变得容易,但这些默认情况下是强制性的。 虽然这对于大多数情况来说已经足够了,但在某些情况下可选参数会很有用。
使用可选参数创建路由
与常规参数一样,声明可选参数只是 Route 的 path 属性的问题; 任何以问号结尾的参数都将被视为可选参数:
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
{/* Optional parameters are defined by placing a question mark at the end of a parameter. */}
{/* In this case, `line` is an optional parameter. */}
{/* Optional parameters will be passed to the component, but will be undefined if not present in the URL. */}
<Route path="/Lyrics/:song/:line?" component={LyricSheet}/>
</div>
</BrowserRouter>
);
}
}
如果路由与路径匹配,则将呈现路由,无论是否带有可选参数。 所以 '/Lyrics/Spoonman' 和 '/Lyrics/Spoonman/3' 都会被接受。
使用可选参数
可选参数与强制参数一起作为道具传递。 但如果它们不在 URL 中,它们将是未定义的:
export default function LyricSheet({ match }) {
const {line, song} = match.params;
// Since `line` is an optional parameter, it'll either be undefined or a string.
const lineNumber = line ? parseInt(line, 10) : -1;
// Get the lyrics to the song.
const lyrics = getLyrics(song)
// Map the lyrics to components. If `index` is `lineNumber`, set `highlight` to `true`.
.map((lyric, index) => (<LyricLine highlight={index === lineNumber} key={index} lyric={lyric} />));
return (
<div>{lyrics}</div>
);
}
该组件将被渲染以显示 song 的歌词。 如果定义了可选参数 line,则该行将突出显示。 如果您浏览过 GitHub 上的文件,您可能已经看到过类似的内容。
如果您想了解有关 React 的更多信息,请查看我们的 如何在 React.js 中编码,或查看 我们的 React 主题页面 以了解练习和编程项目。