【发布时间】:2019-03-07 14:07:26
【问题描述】:
所以这是我的问题。我在我的 React 路由器中使用 HOC。所以它看起来像这样:
<BrowserRouter>
<div className="main__container">
<Route exact path="/" component={authHOC(MainView)} />
<Route path="/article" component={authHOC(Article)} />
<Route path="/apps" component={authHOC(AppList)} />
</div>
</BrowserRouter>
现在,我想将一些道具传递给我的包装组件。我想要这样的东西:
component={authHOC(Article({ header: true })}
所以将道具传递给我的组件。以上行不通。有没有办法通过?
我的 HOC 组件如下所示:
export default function(ProtectedComponent, addProps) {
return class LoginPage extends Component {
checkUserAuth = async() => {
const token = await api.getAuthToken();
this.setState({ isUserLoggedIn: !!token, loading: false });
};
redirectToAuth = () => <Redirect to="/login" />;
render() {
const { isUserLoggedIn, loading } = this.state;
if(!loading) {
return isUserLoggedIn ? (
<ProtectedComponent {...this.props} {...addProps} />
) : this.redirectToAuth();
}
return null;
}
};
}
【问题讨论】:
-
你的做法不对。观看此视频,您将了解如何使用 HOC。不要将 HOC 传递给路由器,这样做尝试从组件本身传递组件。
-
什么是authHOC?
标签: reactjs