首页 > 解决方案 > 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"
 />
                                                                                                    

`

标签: reactjsreact-router-v5

解决方案


好吧,我希望有一天这对某人有所帮助;-) 这一切都是通过 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"
          >

推荐阅读