如何在反应路由器 dom(v4) 中使路径参数成为可选参数? [英] How to make path param to be optional in react router dom(v4)?

查看:33
本文介绍了如何在反应路由器 dom(v4) 中使路径参数成为可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我认为不正确和多余的代码:

This is my code which I don't think is right and redundant:

<BrowserRouter>
 <Route exact={true} path="/" component={App}/>
 <Route path="/:filter" component={App}/>
</BrowserRouter>

我认为exact={true}是多余的,因为我可以在以前的react路由器版本中简单地做path="/(:filter)"?我不想使用 history.push :(

I think exact={true} is redundant since I can simply do path="/(:filter)" in previous react router versions? I don't wanna use history.push :(

这就是我在页脚组件中使用 NavLink 的方式:

This is how I usd my NavLink in my Footer Component:

const Footer = () => (
  <p>
    Show:
    {" "}
    <FilterLink filter="all"> 
      All 
    </FilterLink>
    {", "}
    <FilterLink filter="active">
      Active
    </FilterLink>
    {", "}
    <FilterLink filter="completed">
      Completed
    </FilterLink>
  </p>
);

和我的 FilterLink:

and my FilterLink:

const FilterLink = ({ filter, children }) => (
  <NavLink 
    to={ filter === 'all' ? '' : filter }
    activeStyle={{
      textDecoration: 'none',
      color: 'red'
    }}
  >
  {children}
  </NavLink>
);

路径在变,例如:localhost:3000/active 但是样式没有影响,但是影响了all?当我在 localhost:3000/?

The path is changing, example: localhost:3000/active but the style has no effect, but it affects the all? when I am on localhost:3000/?

推荐答案

在 react-router v4 中你可以定义一个可选的路径参数,如

In react-router v4 you can defined an optional path parameter like

<BrowserRouter>
 <Route path="/:filter?" component={App}/>
</BrowserRouter>

路径参数必须按照 npm 包的方式定义 path-to-regexp 理解为 反应路由器文档

Path parameter must be defined in a manner which is as per the npm package path-to-regexp understands as mentioned in the react-router docs

这篇关于如何在反应路由器 dom(v4) 中使路径参数成为可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆