简体   繁体   English

ReactJS TypeError:无法读取未定义的属性“历史”

[英]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:我的 NavigationService.js 具有以下功能:

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

and then i got my Welcome.jsx which has :然后我得到了我的 Welcome.jsx,它有:

 <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" ,所以现在在我的 .js 文件中,它给了我一个错误:“TypeError:无法读取未定义的属性‘历史’”,

should i do the .js file a Component or anything since in doenst recognize the history我应该做 .js 文件一个组件或任何东西,因为在 doenst 识别历史

I'm guessing you are using React Router for your routing solution.我猜你正在使用React Router作为你的路由解决方案。 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.但是,如果您想这样做,您需要将当前history对象公开给函数。 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.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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