Unable to read undefined property parameters (React Router 4)

I have a route configured to render the component:

<Route exact path="/page/:id" location={this.props.location} key={this.props.location.key} render={({ location }) => (
    <PageStart key={this.props.location.key} />
)} />

Then inside this component (PageStart) I have:

this.props.match.params.id

But this causes an error:

Cannot read property 'params' of undefined

Passing details when just a call is component={}working fine, but not in the rendering function. Why?

+4
source share
3 answers

Since renderyou do not pass the default details sent by the router to a component, such as a match, history, etc.

When you write this:

<PageStart key={this.props.location.key} />

This means the value propsin the component PageStart.

Write this:

render = {props => <PageStart {...props} key={this.props.location.key} /> } />

Now it {...props}will pass all the value to the component PageStart.

+2
source

, match prop - undefined. , match prop:

<PageStart key={this.props.location.key} />

, . render -, . , , :

<Route
  exact
  path="/page/:id"
  location={this.props.location}
  key={this.props.location.key}
  render={(props) => (
    <PageStart {...props} key={this.props.location.key} />
  )}
/>
+2

- match PageStart. key, match. :

<Route 
    exact 
    path="/page/:id" 
    location={this.props.location} 
    key={this.props.location.key} 
    render={({ 
        location, 
        match 
    }) => (
        <PageStart key={this.props.location.key} match={match} />
    )} 
/>
+1

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


All Articles