您如何传递道具并在React上下文中使用HOC

时间:2018-08-11 15:37:17

标签: reactjs

我需要做这样的事情

const CreateActivity = (props) => (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow  email={authUser.email} {...props}/>
  }
</AuthUserContext.Consumer>

const authCondition = (authUser) => !!authUser;
export default withAuthorization(authCondition)(CreateActivity);

这样我可以在createActivity上正确使用我的HOC组件,但在CreateActivityShow上显示this.props仅具有this.props.email,而没有url参数,我应该具有this.props.match ...

我尝试过这种方式

  export default props =>  (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow {...props} email={authUser.email}/>
  }
</AuthUserContext.Consumer>
)

现在我有道具了,但是我不知道如何在这里使用我的HOC

有没有办法同时做这两项?

编辑:

我已经尝试过了

 export default withAuthorization(authCondition)( props =>  (
<AuthUserContext.Consumer>
  {authUser =>
    <CreateActivityShow {...props} email={authUser.email}/>
  }
</AuthUserContext.Consumer>
))

现在我的组件再次被withAuthorization封装,但是现在道具没有被传递,我也不知道为什么...

这是我的HOC

const withAuthorization = (authCondition) => (Component) => {
  class WithAuthorization extends React.Component {
  componentDidMount() {
    firebase.auth.onAuthStateChanged(authUser => {
      if (!authCondition(authUser)) {
        this.props.history.push(routes.SIGN_IN);
      }
    });
  }

render() {
  return (
    <AuthUserContext.Consumer>
      {authUser => authUser ? <Component /> : null}
    </AuthUserContext.Consumer>
  );
  }
}

return withRouter(WithAuthorization);
}

export default withAuthorization;

1 个答案:

答案 0 :(得分:1)

是的,所以问题出在WithAuthorization组件中,您没有将HOC收到的道具传递给渲染的组件。你会这样写

const withAuthorization = (authCondition) => (Component) => {

    class WithAuthorization extends React.Component {
      componentDidMount() {
        firebase.auth.onAuthStateChanged(authUser => {
          if (!authCondition(authUser)) {
            this.props.history.push(routes.SIGN_IN);
          }
        });
      }

        render() {
          return (
            <AuthUserContext.Consumer>
              {authUser => authUser ? <Component {...this.props}/> : null}
            </AuthUserContext.Consumer>
          );
        }

    }

    return withRouter(WithAuthorization);
}

export default withAuthorization;