嗨,我正在创建我的第一个HOC反应,但遇到了麻烦。我在HOC类中导入Contentservice,并且有一个由WithBackend包装的简单Page类。
当我使用react Route导航到页面组件时,出现错误:
TypeError: Cannot read property 'getPage' of undefined
当我调试代码时,我可以看到该服务在构造函数中可用,但是当它进入getPage方法时,我得到了alert(id),但是它在网上中断了
this.service.getPage(id);
这是包装函数:
import React from "react";
import ContentService from "./ContentService";
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.service = new ContentService();
}
getPage(id) {
alert(id);
this.service.getPage(id);
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
export default WithBackend;
这是包装的组件:
import React, { Component } from "react";
import WithBackend from "./WithBackend";
class PageX extends Component {
render() {
return (
<div>
<h2>Home</h2>
</div>
);
}
componentDidMount() {
this.props.getPage("123");
}
}
const Page = WithBackend(PageX);
export default Page;
这是ContentService类:
class ContentService {
getPage(id) {
alert(id);
return "Some page";
}
}
export default ContentService;
谁能看到我做错了吗?另外,我只是将页面的名称更改为PageX,因此如果页面名称被Page包裹,则可以导入。这有必要吗?我宁愿将整个页面命名为page。
非常感谢您的帮助。
将以下内容添加到您的代码中
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.service = new ContentService();
this.getPage = this.getPage.bind(this) // <-- Add this
}
getPage(id) {
alert(id);
this.service.getPage(id);
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
我也鼓励您阅读有关此绑定在javascript中的工作方式的信息。这是我喜欢的博客的链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句