【问题标题】:How to pass props with HOC invocation如何通过 HOC 调用传递道具
【发布时间】: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


【解决方案1】:

不应像Article({ header: true }) 那样直接调用组件,除非this is done on purpose

高阶组件可以接受一个组件和被包装组件使用的附加参数,如the guide所示,例如:

<Route exact path="/" component={authHOC(MainView, { header: true })} />

const authHOC = (Comp, props) => <Comp {...props}/>;

如果authHOC是无法修改的第三方HOC,应提供增强组件:

<Route exact path="/" component={
  authHOC(props => <MainView {...props} header={true} />)
} />

【讨论】:

  • 您好,谢谢您的回答。出于某种原因,我在包装的组件中看不到我的 addProps - {...addProps}。这是为什么?它只是另一个功能......
  • 我之前没有在问题中看到更新的代码,但对我来说看起来没问题。 addProps 应该添加到包装的组件中。你能用演示复制这个问题吗?
猜你喜欢
  • 2021-04-01
  • 1970-01-01
  • 2022-01-10
  • 2022-01-19
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
相关资源
最近更新 更多