Pass props through a higher order component from a Route

戏子无情 提交于 2019-12-21 07:58:10

问题


I have a problem with my Higher Order Component. I am trying to pass props from a <Layout /> component down a route (React Router v4). The components specified in the routes are wrapped by a HOC, but the props that I pass never reaches the component.

Also, I can't use the HOC without using export default () => MyHOC(MyComponent). I can't figure out why, but that might have something to do with it?

Layout.js

const Layout = ({ location, initialData, routeData, authenticateUser }) => (
  <Wrapper>
    <Container>
        <Switch>
          // how do I get these props passed through the HOC? render instead of component made no difference.
          <Route exact path="/pages/page-one" component={() => <PageOne routeData={routeData} title="PageOne" />} />
          <Route exact path="/pages/page-two" component={() => <PageTwo routeData={routeData} title="PageTwo" />} />
          <Route component={NotFound} />
        </Switch>
    </Container>
  </Wrapper>
)

export default Layout

Page.js

// I've tried swapping to (WrappedComponent) => (props) without success
const Page = (props) => (WrappedComponent) => {
 const renderHeader = props.header
   ? <Header title={props.headerTitle} />
   : false
 return (
   <Wrapper>
     {renderHeader}
     <Container withHeader={props.header}>
       <WrappedComponent />
     </Container>
   </Wrapper>
 )
}

export default Page

PageOne.js

class PageOne extends React.Component {
  render() {
    return (
      <Content>
        <Title>{this.props.title}</Title> // <----- not working!
        {JSON.stringify(this.props.routeData, null, 4)} // <---- not working!
      </Content>
    )
  }
}

export default () => Page({ header: true, headerTitle: 'header title' })(PageOne)

// does not work without () => Page
// when using just export default Page I get the "Invariant Violation: Element type is invalid: 
// expected a string (for built-in components) or a class/function (for composite components)
// but got: object. Check the render method of Route." error.

回答1:


You need one more arrow to make your Page to be a HOC. It takes params, wrapped component and has to return a component. Yours were rendering after getting WrappedComponent

const Page = (props) => (WrappedComponent) => (moreProps) => {
 const renderHeader = props.header
   ? <Header title={props.headerTitle} />
   : false
 return (
   <Wrapper>
     {renderHeader}
     <Container withHeader={props.header}>
       <WrappedComponent {...moreProps} />
     </Container>
   </Wrapper>
 )
}

Now you can use it like this

export default Page({ header: true, headerTitle: 'header title' })(PageOne)


来源:https://stackoverflow.com/questions/44694176/pass-props-through-a-higher-order-component-from-a-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!