Javascript 通过编程导航到路由

Javascript 通过编程导航到路由,javascript,react-router,Javascript,React Router,我有一些恒定的: const routes = { route1: '/route-1' }; <Switch> <Route exact path={`${routes.route1}/:id`} component={SomeComponent}> </Switch> 是这样吗 或者我应该这样做: history.push(routes.route1, { id: myId }); 原因第二个不起作用第一个是正确的。第二个实际指定了路

我有一些恒定的:

const routes = {
    route1: '/route-1'
};

<Switch>
    <Route exact path={`${routes.route1}/:id`} component={SomeComponent}>
</Switch>
是这样吗

或者我应该这样做:

history.push(routes.route1, { id: myId });

原因第二个不起作用

第一个是正确的。第二个实际指定了路由的
状态
。因此,在导航页面中,您会发现
id
位于
state
下,其中state来自:

const{state:{id}}=useLocation()

第一个将为您提供参数
id

const{id}=useParams()


useParams()
useLocation()
是可以在组件上使用的挂钩

react路由器有一个用于此的组件第二个组件不工作,因为它与
历史记录.push
api不兼容。Ref:and@Reyno,但我不想在onclick事件中导航,编程上,不是这样declarative@Yoshi所以你可以推送从URL中隐藏的状态,但是你应该在URL中传递参数,对吗?我这么说,是的。
history.push(routes.route1, { id: myId });