gpt4 book ai didi

reactjs - 使用默认值响应路由参数

转载 作者:行者123 更新时间:2023-12-04 00:13:48 25 4
gpt4 key购买 nike

我正在将 react 功能组件与 react 路由器 v5 一起使用。我正在使用 useParam 函数来获取参数。当参数不可用或未定义时,如何设置参数的默认值。
我的路由器代码

<Switch>
// ....
// ....
<Route path="/users/:userId?" component={UserInfo} />
// ....
</Switch>
我的组件代码
export const UserInfo = (props) => {
const {userId} = useParams()


// ... other codes
}
我在调用 http://localhost:3000/users/时收到 undefined
任何想法都会有所帮助。

最佳答案

如果您的 Switch 中没有与“/users”匹配的其他路由,则可以为“/users/:userId”路径的解构 params 对象提供回退值。

export const UserInfo = (props) => {
const { userId = /* fallback value */ } = useParams();

// ... other codes
}

关于reactjs - 使用默认值响应路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65678961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com