何时使用 HOC。何时使用 Function as child
When to use HOC. When to use Function as child
我很困惑。我不久前才了解 HOC。尽管我还不能做出一个非常好的(有用的)HOC,但我明白它是如何工作的。 (好吧,如果有人可以用 HOC 给我一些现实世界的解决方案,我会感谢它 :D)。但是然后……我现在刚读到的东西:作为child
的功能
return (
<div>
{this.props.children(this.state.visible)}
</div>
)
{(visible) =>
visible ?
<Placeholder/> : ''
}
它看起来非常酷,但就像 HOC 一样,我不确定我可以在哪里使用它,以及我可以在哪里使用它而不是 HOC(反之亦然)。
(实际上,我对函数 Child 更困惑(知道它是如何工作的)。我不知道我应该在哪里使用它,以及为什么要超过 HOC)。
我将 HOC 用于 PrivateRouting。这是检查用户是否通过 redux 进行身份验证的示例。
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import Header from '../components/Header';
export const PrivateRoute = ({
isAuthenticated,
component: Component,
...rest
}) => (
<Route {...rest} component={(props) => (
isAuthenticated
? (
<div>
<Header />
<Component {...props} />
</div>)
: (<Redirect to="/" />)
)} />
);
const mapStateToProps = (state) => ({
isAuthenticated: !!state.auth.uid
});
export default connect(mapStateToProps)(PrivateRoute);
// 用法
<PrivateRoute path="/edit/:id" component={SomeEditPage} />
如果用户通过身份验证,那么他可以去编辑一些东西,如果没有,它将把他路由到 home Route ('/')
我很困惑。我不久前才了解 HOC。尽管我还不能做出一个非常好的(有用的)HOC,但我明白它是如何工作的。 (好吧,如果有人可以用 HOC 给我一些现实世界的解决方案,我会感谢它 :D)。但是然后……我现在刚读到的东西:作为child
的功能return (
<div>
{this.props.children(this.state.visible)}
</div>
)
{(visible) =>
visible ?
<Placeholder/> : ''
}
它看起来非常酷,但就像 HOC 一样,我不确定我可以在哪里使用它,以及我可以在哪里使用它而不是 HOC(反之亦然)。
(实际上,我对函数 Child 更困惑(知道它是如何工作的)。我不知道我应该在哪里使用它,以及为什么要超过 HOC)。
我将 HOC 用于 PrivateRouting。这是检查用户是否通过 redux 进行身份验证的示例。
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import Header from '../components/Header';
export const PrivateRoute = ({
isAuthenticated,
component: Component,
...rest
}) => (
<Route {...rest} component={(props) => (
isAuthenticated
? (
<div>
<Header />
<Component {...props} />
</div>)
: (<Redirect to="/" />)
)} />
);
const mapStateToProps = (state) => ({
isAuthenticated: !!state.auth.uid
});
export default connect(mapStateToProps)(PrivateRoute);
// 用法
<PrivateRoute path="/edit/:id" component={SomeEditPage} />
如果用户通过身份验证,那么他可以去编辑一些东西,如果没有,它将把他路由到 home Route ('/')