reactjs - React-router v5.2 NavLink active 未按预期工作
问题描述
我有像“/works/:type/:id”这样的路线。不应严格匹配所有“/works/whatever/whatever”路径,因为最后两个路径是动态值。但这种情况并非如此!我也在尝试使用 isActive 强制执行,但也没有运气。一旦 ON 总是 ON 行为就会启动,因为不会发生重新加载。即使使用“useEffect”钩子,我们也可以检测到 URL 的变化并正确更新 isActive,一次 ON 总是 ON。有人可以让我朝着正确的方向前进,请问如何处理。
`<NavLink
className="nav-link"
activeStyle={{ color: "#f5d62d" }}
isActive={() => isWorks}
to="/works/moving-image/intro"
/>
`
解决方案
好吧,我希望有一天这对某人有所帮助;-) 这一切都是通过 react-router 中的 useEffect 和 withRouter 实现的。
import { withRouter, NavLink } from "react-router-dom";
export default withRouter(function SomeFuntionComponent({ location }) {
const [currentPath, setCurrentPath] = useState(location.pathname);
useEffect(() => {
const { pathname } = location;
console.log("New path:", pathname);
setCurrentPath(pathname);
}, [location.pathname]);
然后最后在您的 NavLink 上添加 isActive 如下
isActive={() => (currentPath.indexOf("/some-link") > -1)}
<NavLink
strict
className="nav-link"
isActive={() => (currentPath.indexOf("/moving") > -1)}
activeStyle={{ color: "white" }}
to="/some-link"
>
推荐阅读
- xml - 如何使用 PowerShell 从 xml 文件中获取特定信息
- scrapy - 如何防止网站被 Scrapy 刮掉
- asp.net - 从虚拟目录获取根目录
- php - as3 - php - mysql 没有答案
- objective-c - 无法从日文文本字符串转换为 NSUTF8StringEncoding
- batch-file - 为什么批处理文件执行仅在 Jenkins 中失败,并显示压缩的 .rar 文件不存在的错误消息?
- javascript - 从ckeditor 5获取xml
- python - 从熊猫中的特定格式更改日期?
- python - 使用 pandas 对每日数据进行时间分析
- python - 将参数传递给参数到模板中