【发布时间】: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) => ({ > 16 | sessionId: state.auth.userInfo.authUserInfo.sessionId 17 | }) -
你的属性
auth.userInfo.authUserInfo的redux状态在这个组件被渲染之前没有定义 -
嗯,我想了这么多 - 你有答案可以和我分享吗?
-
我不知道您的应用程序的其余部分是如何工作的。由您决定在哪里设置这个 redux 状态属性
auth.userInfo.authUserInfo并确保在渲染组件之前设置它
标签: reactjs redux higher-order-components