【问题标题】:How to make path param to be optional in react router dom(v4)?如何在反应路由器dom(v4)中使路径参数成为可选?
【发布时间】:2017-06-09 15:59:22
【问题描述】:

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

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

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

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

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

还有我的 FilterLink:

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

路径在变化,例如:localhost:3000/active 但是样式没有效果,但是影响全部?当我在 localhost:3000/?

【问题讨论】:

    标签: reactjs react-router react-router-v4


    【解决方案1】:

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

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

    必须按照 npm 包 path-to-regexp 理解的方式定义路径参数,如 react-router docs

    中所述

    【讨论】:

    • 当我应用 activeStyle 时,它​​不能在我的 localhost:3000 上运行,也不能在其他过滤器上运行?
    • 你在应用activeStyle时是什么意思
    • 如果你不添加活动样式那么
    • 都是一样的样式,只是在下面加了下划线,但是我想加activeStyle,我做不到
    • 也许
    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2017-11-12
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多