简体   繁体   中英

ReactJS Route Components/Render

I created a simple booking app with 3 files, App.js , Booked.js (1st child) and Details.js (2nd child)
I'm trying to access App.js to delete a data using the 2nd child( Detail.js ) but I can't proceed because it throws me an error of

"TypeError: Cannot read property 'state' of undefined"

Whenever I try to add function to a Route Component to access App.js

This is the main page https://i.stack.imgur.com/4PrM8.png
When I click the data which is in Booked.js i get redirected to Details.js to view the specific data https://i.stack.imgur.com/H2EnL.png

Using this code, a Route with component works

<Route path="/details" component={Details} /> 

But after adding a function gives me an error

<Route path="/details" component={ () => <Details delBook={this.delBook} /> } />

or

<Route path="/details" render={()=><Details delBook={this.delBook}/>}/> 

Link in Booking.js

 <Link
  to={{
  pathname: "/details",
  state: {
  id: booking.id,
  fname: booking.fname,
  lname: booking.lname,
  email: booking.email,
  ddate: booking.ddate,
  ttime: booking.ttime
  }
  }}
  key={booking.id} 
  style={linkStyle}>

In Details.js where the error throws.

 state = {
    id: this.props.location.state.id,
    fname:  this.props.location.state.fname,
    lname:  this.props.location.state.lname,
    email: this.props.location.state.email,
    ddate: this.props.location.state.ddate,
    ttime: this.props.location.state.ttime,
}

Can someone help and explain why is this happening ? Any solution or alternatives ? TIA!

You need to bind this when passing it as a prop. Also it's a good idea to pass the router's props as well:

<Route path="/details" component={ (routerProps) => <Details delBook={this.delBook.bind(this)} {...routerProps} />  } />

Also in Details.js you should use props directly, instead from this :

class Details extends React.Component {
  constructor(props) {  // Use constructor to initialise `this` properly
    super(props);

    this.state = {
      id: props.location.state.id,
      fname: props.location.state.fname,
      lname: props.location.state.lname,
      email: props.location.state.email,
      ddate: props.location.state.ddate,
      ttime: props.location.state.ttime
    };
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM