【问题标题】:How to get access to state with higher order component如何使用高阶组件访问状态
【发布时间】:2019-04-27 02:22:11
【问题描述】:

我想创建一个高阶组件来检查用户是否已登录。如果有,我会显示该组件,如果没有,我想将他们重定向到登录页面。

有人可以解释我在这里做错了什么吗?

这是 HOC:

import React from 'react';
import { connect } from 'react-redux';

const withAuthentication = (Component) => {
  class WithAuthentication extends React.Component {
    componentDidMount() {
      console.log(this.props.sessionId);
    }

    render() {
      return this.props.sessionId ? <Component {...this.props} /> : null;
    }
  }

  const mapStateToProps = (state) => ({
    sessionId: state.auth.userInfo.authUserInfo.sessionId
  })
  return connect(mapStateToProps, null)(WithAuthentication);
}

export default withAuthentication;

那我这样称呼它:

....
import withAuthentication from './containers/withAuthentication';
const Hello = () => <h1> Hello</h1>;
....
<Route path="/" component={ withAuthentication(Hello) }/>

我删除了更多我认为与此无关的代码...

TIA 为您提供帮助!

更新:导致问题的代码似乎是这样的:

const mapStateToProps = (state) => ({
sessionId: state.auth.userInfo.authUserInfo.sessionId
})

错误:TypeError: Cannot read property 'sessionId' of undefined

【问题讨论】:

  • 什么错误/问题或它是如何工作不正确的?
  • 出现的错误是:TypeError: Cannot read property 'sessionId' of undefined指向这个代码块:const mapStateToProps = (state) =&gt; ({ &gt; 16 | sessionId: state.auth.userInfo.authUserInfo.sessionId 17 | })
  • 你的属性auth.userInfo.authUserInfo的redux状态在这个组件被渲染之前没有定义
  • 嗯,我想了这么多 - 你有答案可以和我分享吗?
  • 我不知道您的应用程序的其余部分是如何工作的。由您决定在哪里设置这个 redux 状态属性 auth.userInfo.authUserInfo 并确保在渲染组件之前设置它

标签: reactjs redux higher-order-components


【解决方案1】:

所以基本上,你在将一个组件嵌套到另一个组件中所做的事情,即一个功能组件在经过一些逻辑级别验证后返回另一个组件。 你在做什么似乎很好。您应该能够在这样的功能组件中访问道具(而不是状态)

let aComponent(props)=>{
    return <p>{props.name}'s logged in status is {props.loggedIn}</p>
}

如果你正在使用这样的组件

<aComponent title="Hello" loggedIn={this.props.isLoggedIn}/> //isLoggedIn from redux store

此外,如果 withAuthentication 中的逻辑/身份验证验证失败,您应该调用路由器 API 以导航到您想要的页面。 IE。 如果您使用的是react-router,则应该调用它

this.props.router.push('/login')

【讨论】:

  • 您好 Manjot,感谢您的回复。很抱歉,这有点难以理解 - 你是说登录检查应该发生在 hoc 的孩子身上吗?这会否定 HOC 的必要性吗?
  • 嗨@AtlanteAvila,在那里看到你的错误。尝试在您的 auth reducer 中初始化 userInfo 状态,如下所示。 initialState= { userInfo:{ sessionId:'' } }
  • 发生错误是因为,在组件访问之前,您的 auth 操作无法填充 userInfo 的 auth reducer 状态。如果你也能分享你的 auth reducer sn-p 那就更好了
猜你喜欢
  • 2019-09-22
  • 1970-01-01
  • 2016-12-08
  • 2018-12-30
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多