我想创建一个更高阶的组件来检查用户是否已登录。如果他们已经登录,我会显示该组件,如果没有,我想将他们重定向到登录页面。
有人可以解释一下我在这里做错了什么吗?
这是 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:无法读取未定义的属性“sessionId”
最佳答案
基本上,您正在将一个组件嵌套到另一个组件中,即功能组件在经过某种逻辑级别验证后返回另一个组件。 你正在做的事情看起来不错。您应该能够在像这样的功能组件中访问 Prop (而不是状态)
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')
关于reactjs - 如何使用高阶组件访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464181/