简体   繁体   中英

Why is state undefined when passed through React Router Link Component?

I am trying to pass props through the React Router Link Component but the state remains undefined, does anyone have an idea of why?

The Route:

<Route path="/movie" component={Movie} render={props => 
<Movie {...props} />} />

The Link:

<Link to={{ pathname: '/movie', state: { fromMovieList: true}}} > 
Title </Link>

The component rendered from the path "/movie"

class Movie extends React.Component {

  render () {
    console.log(this.props.location.state); // undefined
    return (
      <div> Hello </div>
        )
      }
    }

export default Movie;

You must wrap the Movie component with withRouter ;

You can get access to the history object's properties and the closest Route's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

export default withRouter(Movie);

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