【发布时间】:2020-08-11 18:38:18
【问题描述】:
我在从父组件访问参数 ID 时遇到问题。我知道道具是从父组件传递到子组件的,因此例如仪表板组件可以访问 id,但侧边栏组件不能。话虽如此,有什么方法可以为侧边栏提供该 ID,以便在选择选项卡时可以适当地路由。
Signin.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,这会将用户推送到主要组件。
Main.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”应该与上面的相同,只需附加“/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`);
}
};
感谢您的帮助!!
【问题讨论】:
-
问题的标题有点不对劲。为了帮助其他人搜索相关问题,请考虑重写标题,例如如何从父组件访问路由信息
标签: javascript reactjs react-router