问题描述
在使用 antd 的过程中,突然发现 <Menu> 中选中状态的元素并没有随路由变化而改变
此时相关代码如下:
<Menu
theme="light"
mode="horizontal"
defaultSelectedKeys={
USER_MENU_LIST[0].name}
>
{
this.currUser.type && ADMIN_MENU_LIST.map((item) =>
<Menu.Item key={
item.path}>
<NavLink to={
item.path}>
<span>{
item.name}</span>
</NavLink>
</Menu.Item>
)}
</Menu>
解决办法
搜寻已有的 issue,其中的链接已失效,其中的建议并没有成功解决笔者的问题
网络上查找相关文章,提到的主要关键字有:history
, withRouter
,selectedKeys
逐点击破
selectedKeys
其为 antd 提供的API,用于修改当前选中的元素withRouter
路由组件可以直接获取match
,history
,location
,非路由组件需要使用wiithRouter
来获取history
监听浏览器地址变化,转化为location
文档传送门
以下为修改后的相关代码,部分省略
①使用withRouter
, 并将selectedKeys
设为当前this.props.location.pathname
值
使用tihs.props
而非history
, 因为后者容易变动
...