简体   繁体   中英

ReactJS TypeError: Cannot read property 'history' of undefined

So i try to make a "Service" which helps me with some small tasks,

my NavigationService.js has following function:

 redirectView = (view) => { this.props.history.push(`/${view}`) }

and then i got my Welcome.jsx which has :

 <BtnRectangularBorder> <BtnRectangular className="battle-shonen-color btn-rectangular-md-size btn-rectangular-primary" title="Cards Overview" onClick={NavigationService.redirectView("/cards-overview")} /> </BtnRectangularBorder>

so now in my .js file it gives me an error : "TypeError: Cannot read property 'history' of undefined" ,

should i do the .js file a Component or anything since in doenst recognize the history

I'm guessing you are using React Router for your routing solution. I'm not certain how useful it would be to wrap a utility function around it, as it is already a utility function. However, if you would like to do so you would need to expose the current history object to the function. Something like this:

const NavigationService = {
  redirectView = (history, view) => {
    history.push(`/${view}`)
  }
}
const MyComponent = withRouter(({ history }) => (
  <BtnRectangularBorder>
    <BtnRectangular 
      className="battle-shonen-color btn-rectangular-md-size btn-rectangular-primary" 
      title="Cards Overview" 
      onClick={NavigationService.redirectView(history, "/cards-overview")} 
    />
  </BtnRectangularBorder>
));

Usually I'm all about wrapping things in utilities, but I'm honestly not sure what it buys you in this case. Hope that helps.

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