How to make path param to be optional in react router dom(v4)?

≡放荡痞女 提交于 2019-12-07 18:41:49

问题


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>

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 :(

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>
);

and my FilterLink:

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

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/?


回答1:


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

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

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



来源:https://stackoverflow.com/questions/44462158/how-to-make-path-param-to-be-optional-in-react-router-domv4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!