【发布时间】:2017-09-01 07:54:51
【问题描述】:
假设我有一些“页面”组件,它需要从服务器请求数据。它请求的数据将取决于当前用户是否经过身份验证。此外,在登录的情况下,页面将需要重新加载数据。我的问题是,如何使用 HOC 而不是继承来完成这样的事情?
为了说明这个问题,我将演示一个使用继承的解决方案。该程序将具有以下对象。我将省略样板代码。
-
session:一个EventEmitter,在会话更改(登录或注销)时发出start。 -
Page:所有页面都继承自的超类 -
MyPage:本例中Page的子类 -
API: 将是一个用于从服务器检索数据的 API 类
代码如下:
// Page superclass
class Page extends React.Component {
componentWillMount() {
session.on("start", this.loadData);
this.loadData();
}
loadData() {
// this method is overwritten in subclasses
}
}
// MyPage subclass
class MyPage extends Page {
loadData() {
if(session.isAuthenticated()) {
API.loadPrivateData();
} else {
API.loadPublicData();
}
}
}
这是一个使用 HOC 的解决方案,但似乎不如继承优雅。它仍然要求每个“子类”页面都有一个方法loadData,并且它要求在每个“子类”componentWillMount 中调用该方法。
// Page HOC
function Page(WrappedComponent) {
return class EnhancedPage extends React.Component {
componentWillMount() {
session.on("start", this.loadData);
// this._page.loadData() will fail here
// since this._page is undefined until rendering finishes
}
loadData() {
this._page.loadData();
}
render() {
return <WrappedComponent {...props} ref={(e) => { this._page = e; }} />
}
}
}
// MyPage
class MyPage extends React.Component {
componentWillMount() {
this.loadData();
}
loadData() {
if(session.isAuthenticated()) {
API.loadPrivateData();
} else {
API.loadPublicData();
}
}
}
const component = Page(MyPage)
// what would make sense here is to have a method something like
// const component = Page(MyPage, () => MyPage.loadData())
// but then the MyPage.loadData logic would need to be defined
// elsewhere
这种模式经常发生:我想加载一些数据,然后在会话更改时重新加载。我想了解完成相同任务的“反应”方式。
编辑:我不想通过 HOC 传递用户名或“loggedIn”标志。也就是说像<WrappedComponent isLoggedIn={session.isAuthenticated()} {...props} /> 这样的东西不会在这里剪掉。将 API 逻辑绑定到 props 需要我检查 MyPage.componentWillUpdate() 中的更改。
【问题讨论】:
-
@NathanP。这是一个类似的问题,但我认为有几个重要的区别。 1)我没有使用redux,这只是原始反应。 2) 我不是试图通过登录标志或用户名进行渲染,而是在会话状态发生变化时尝试执行一些特定于组件的操作。
标签: javascript reactjs inheritance higher-order-functions higher-order-components