如果您遇到导航菜单正常工作的问题,但当您单击链接和路线更改时它没有正确更新,但如果您按 F5 可以正常工作,您可以执行以下操作:
这可能是因为您正在使用 Redux,shouldComponentUpdate
它的功能上有一个 Lifecycle 方法connect
。您可能将 Nav 组件包装在connect
. 这一切都很好。shouldComponentUpdate
是什么毁了你的生活。
要修复,只需将路由器带入您的mapStateToProps
功能:
// This lets shouldComponentUpdate know that the route changed,
// which allows the Nav to re-render properly when the route changes, woot!
const mapStateToProps = (state) => {
return {
router: state.router,
}
}
// or, if you prefer pro style destructure shorthand:
const mapStateToProps = ({ router }) => ({ router })
如果您不太确定state.router
来自哪里,它来自您组合减速器的文件,您将看到如下内容:
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import authReducer from './components/auth/auth_reducer'
export default combineReducers({
router: routerReducer,
auth: authReducer,
})
这是一个漂亮的baller Nav Link的一些HTML和CSS:
HTML
<ul id="Nav_menu">
<li>
<NavLink
to="/home"
className="Nav_link"
activeClassName="activeRoute"
activeStyle={{ color: 'teal' }}
>
HOME
</NavLink>
</li>
<li>
<NavLink
to="/products"
className="Nav_link"
activeClassName="activeRoute"
activeStyle={{ color: 'teal' }}
>
PRODUCTS
</NavLink>
</li>
</ul>
注意:如果您要链接到"/"
,请将exact
道具放在 NavLink 上。
CSS
#Nav_menu {
display: flex;
flex-direction: row;
width: 100%;
height: 100%;
list-style-type: none;
margin: 0;
padding: 0;
}
.Nav_link:link {
color: #fff;
font-size: 1.6rem;
line-height: 1.6rem;
text-decoration: none;
}
.Nav_link:visited {
color: #fff;
}
.Nav_link:hover {
color: yellow;
}
.Nav_link:active {
color: teal;
}
.activeRoute {
background-color: yellow;
border-bottom: 0.4rem solid teal;
cursor: not-allowed;
}
请注意activeStyle
HTML 标记中的内容。这是我可以更改活动路线/链接上文本颜色的唯一方法。color: teal;
当我放入activeRoute
CSS 类时它不起作用。在另一个选项卡中打开它:https ://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md
如果你不知道我为什么rem
用px
. 这是您研究网络可访问性和基础的绝佳机会font-size: 10px;
。
保持健康,玩得开心。