【问题标题】:Wrap a React route render function in a HOC在 HOC 中包装一个 React 路由渲染函数
【发布时间】:2018-02-03 06:44:30
【问题描述】:

我正在使用 React-Router 4 创建一些路由。 (它使用来自official docsPrivateRoute 组件,但这与这个问题无关。)

<HashRouter>    
    <Switch>
        <PrivateRoute exact path='/' component={Wrapper(Home)} />
        <Route exact path='/login' render={(props) => <Login authenticate={this.authenticate} {...props} />} />
        <PrivateRoute exact path='/clients' component={Wrapper(Clients)} />
    </Switch>
</HashRouter>

如您所见,HomeClients 组件封装在 HOC 中。目前这没有任何作用:

const Wrapper = (Page) => {
    return (props) => (
        <div className="page">
            <p>This should be on every page</p>
            <Page {...props} />
        </div>
    );
}

这很好用。我想不通的是如何将 Login 路由包装在同一个 HOC 中。我试过了

<Route exact path='/login' render={(props) => Wrapper(<Login authenticate={this.authenticate} {...props} />)} />

但这会返回错误:

Route.render():必须返回一个有效的 React 元素(或 null)。

【问题讨论】:

    标签: javascript reactjs react-router higher-order-components


    【解决方案1】:

    你可以试试这样吗:

    <Route exact path='/login' render={(props) => Wrapper(Login)({...props, authenticate: this.authenticate})} />
    

    因为现在 Wrapper HOC 正在返回一个函数,但反应元素是预期的。要获得 react 元素,我们需要使用所需的道具调用此函数,这似乎是添加额外道具 this.authenticate 的好地方。

    这是我做的一个快速的 sn-p: https://stackblitz.com/edit/react-zestnq

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 2019-05-09
      • 2018-10-18
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多