How to get parameters in a component in dom v4 response router?

I have this code:

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

The filter parameter or `` in the root, presumably, should be based on the details of the application components on previous versions of the reacting router?

This is my code in my application:

const App = ({params}) => {
    return ( // destructure params on props
      <div>
        <AddTodo />
        <VisibleTodoList 
            filter={params.filter || 'all'} // i want to git filter param or assign 'all' on root 
        />
        <Footer />
      </div>
    );
}

I ran this.props.match.params on the console, but it doesn't have it? to help?

+4
source share
4 answers

, Redux Egghead.io, , , , . , React Router v4, , .

⚠️ . , , , react-router-dom (4.1.1 ). - - v4.

-, , React Router v4, , , <Switch>.

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

-, , React Router v4 params , match prop .

const App = ({ match }) => {
    return (
      <div>
        <AddTodo />
        <VisibleTodoList filter={match.params.filter || 'all'} />
        <Footer />
      </div>
    )
}

: mapStateToProps HoC withRouter, Egghead, .

, .

, , ( ).

+5

React Router v4 . . <Switch>, , :

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

. match, params ( , , ):

const App = ({match}) => {
    return ( 
      <div>
        <AddTodo />
        <VisibleTodoList 
            filter={match.params.filter || 'all'} 
        />
        <Footer />
      </div>
    );
}

React Router V4 docs

+4

react-router documentation, props.match.params , .

,

const App = ({match}) => {
    ...
    <VisibleTodoList 
        filter={match.params.filter || 'all'}
    />
    ...
}
+1

, , , , location.pathname, . , param - , , || , , , , location.pathname. , regexp.

0

Source: https://habr.com/ru/post/1678931/


All Articles