Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用默认值反应路由参数_Reactjs_React Router - Fatal编程技术网

Reactjs 使用默认值反应路由参数

Reactjs 使用默认值反应路由参数,reactjs,react-router,Reactjs,React Router,我正在将react功能组件与react路由器v5一起使用。我正在使用useParam函数获取参数。当参数不可用或未定义时,如何设置其默认值 我的路由器代码 <Switch> // .... // .... <Route path="/users/:userId?" component={UserInfo} /> // .... </Switch> 我打电话时发现未定义http://localhost:30

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

我的路由器代码

<Switch>
    // ....
    // .... 
    <Route path="/users/:userId?" component={UserInfo} />
    // ....
</Switch>
我打电话时发现
未定义
http://localhost:3000/users/.


任何想法都会有帮助。

您可以使用
道具来代替路由器中的
useParams()
功能。匹配
并检查条件

反而

const {userId} = useParams()
使用


如果
开关中没有与“/users”匹配的另一个路由,则可以为“/users/:userId”路径的解构params对象提供回退值


您的
交换机
中是否有另一条应与“/用户”匹配的路由?我有另一条精确的
路由,您能否更新您的问题以包括完整的
路由器
和路由?我想你可能只需要调整一些路线的顺序。
const {userId} = useParams()
// assuming 0 is the default value
const userId = props.match?.userId || 0;
export const UserInfo = (props) => {
    const { userId = /* fallback value */ } = useParams();

    // ... other codes 
}