使用默认值响应路由参数
我正在将反应功能组件与反应路由器 v5 一起使用。我正在使用 useParam 函数来获取参数。当参数不可用或未定义时,如何设置参数的默认值。
我的路由器代码
<Switch>
// ....
// ....
<Route path="/users/:userId?" component={UserInfo} />
// ....
</Switch>
我的组件代码
export const UserInfo = (props) => {
const {userId} = useParams()
// ... other codes
}
我undefined在调用 http://localhost:3000/users/ 时得到了。
任何想法都会有所帮助。
回答
如果您的路由中Switch没有与“/users”匹配的其他路由,则可以为“/users/:userId”路径的解构参数对象提供回退值。
export const UserInfo = (props) => {
const { userId = /* fallback value */ } = useParams();
// ... other codes
}