![](/img/trans.png)
[英]How to access parent component properties from a child route component in Angular?
[英]How to access route information from a parent component?
我在从父组件访问参数 id 时遇到问题。 我知道道具是从父组件传递到子组件的,因此例如仪表板组件可以访问 id,但侧边栏组件不能。 话虽如此,是否有任何方法可以为侧边栏提供该 ID,以便在选择选项卡时可以适当地路由。
登录.js
case 'server':
props.history.push('/profile');
break;
case 'manager':
if (user.linkedRestaurants.length > 1) {
props.history.push('/main');
} else if (user.linkedRestaurants.length === 1) {
props.history.push(`/main/${user.linkedRestaurants[0]}`);
} else {
console.log('Nothing for now');
}
break;
default:
console.log('You do not have a role');
}
登录代码评估用户角色,然后相应地路由用户。 例如,当他们是经理时,url 看起来像https://localhost:1111/main/waod1289yu123unb ,这会将用户推送到主要组件。
主.js
return (
<Layout style={{ minHeight: '100vh' }}>
<Sidebar /> <---- I want to be able to access the id param here
<Layout className='site-layout'>
<Header className='site-layout-background' style={{ padding: 0 }} />
<Content style={{ margin: '0 16px' }}>
<Switch>
<Route exact path='/main/:id/dashboard' component={Dashboard} /> <-- I am able to access it here
<Route exact path='/main/:id/staff' component={Staff} />
</Switch>
</Content>
</Layout>
</Layout>
);
};
main.js 组件中有嵌套的路由,因为内容只会显示在侧边栏的右侧。 所以理论上每当有人点击侧边栏中的一个链接时,它会调用下面的句柄路由方法,它应该将用户推送到“新 url”应该与上面的相同,只是 append“/dashboard”例子。 所以https://localhost:1111/main/waod1289yu123unb/dashboard
Sidebar.js
const [collapsed, setCollapsed] = useState(false);
const onCollapse = (collapsed) => {
console.log(collapsed);
setCollapsed(collapsed);
};
const handleRouting = (key) => {
if (key === '1') {
props.history.push('/main/locations');
} else if (key === '2') {
props.history.push(`/main/${????}/dashboard`);
} else if (key === '3') {
props.history.push(`/main/${????}/staff`);
}
};
谢谢你的帮助!!
在您的Sidebar
组件中,您可以使用 react-router-dom 中的matchPath function 访问Dashboard
的 id。
import { matchPath, useLocation } from "react-router-dom";
...
const location = useLocation();
const id = matchPath(props.location, { path: `/main/:id`});
...
const [collapsed, setCollapsed] = useState(false);
const onCollapse = (collapsed) => {
console.log(collapsed);
setCollapsed(collapsed);
};
const handleRouting = (key) => {
if (key === '1') {
props.history.push('/main/locations');
} else if (key === '2') {
props.history.push(`/main/${id}/dashboard`);
} else if (key === '3') {
props.history.push(`/main/${id}/staff`);
}
};
@gdh 是正确的,但是matchPath返回一个 object,要获取该 ID,可以像这样对其进行解构:
const { params: { id } } = matchPath(props.location, { path: `/main/:id`});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.