我已经写了这个HOC来保护我的反应应用程序中的某些区域/路线
import React from "react"
export default (WrappedComponent, AuthenticateComponent) => {
let Protected = (props) => (
props.authenticated
? <WrappedComponent {...props}/>
: <AuthenticateComponent {...props}/>
)
return Protected
}
使用此功能的唯一路径组件是/account
import React from "react"
import { connect } from "react-redux"
import Protected from "../components/Protected"
import LoginContainer from "./LoginContainer"
let AccountContainer = ({children}) => (
React.Children.only(children)
)
export default connect(state => state.account)(Protected(AccountContainer, LoginContainer))
但是我越是看到这个,我越想通过简单地重写AccountContainer
而不使用HOC就可以解决这个问题:
let AccountContainer = (props) => (
props.authenticated
? <WrappedComponent {...props}/>
: <AuthenticateComponent {...props}/>
)
let Protected = (props) => (
props.authenticated
? <props.protectedContent {...props}/>
: <props.authenticateComponent {...props}/>
)
let Protected = (props) => (
props.authenticated
? Child.renderOnly(props.children[0], {...props})/>
: Child.renderOnly(props.children[1], {...props})/>
)
并像这样使用:
render() {
<Protected authenticated={this.props.authenticated}>
<ProfilePage/>
<LoginPage/>
</Protected>
}
我是HOC的方式(重新使用)?