我正在使用这个:-
<Route exact path="/newPost"
component = { withAuthentication(PostForm,props) }
/>
我的HOC接受两个参数并返回一个组件。我想使用Route Render而不是Route Compoment,因为我不想卸载组件。我却无法做到。我在下面做了这样的事情
<Route exact path="/newPost"
// need Auth HOC
render = {(props) =>
{
const MyComponent = withAuthentication(PostForm,props)
return(< MyComponent {...props}/>)
}
/>
这有效,但是未登录的用户也可以访问该页面,而不用将用户带到“ /登录”。我的HOC如下:
export default function withAuthentication(component,data={}){
class Authenticate extends Component{
componentDidMount(){
if(this.props.isAuth === false){
this.props.history.push("/login")
}
}
componentWillUpdate(){
if(this.props.isAuth === false){
this.props.history.push("/login")
}
}
render(){
return <component {...this.props} {...data} />
}
}
function mapStateToProps(state){
return {
isAuth: state.currentUser.isAuth
}
}
return connect(mapStateToProps)(Authenticate)
}
感谢您的帮助。我真的很欣赏。
编辑:目前,我暂时暂时完全删除HOC,以使用渲染。
render = { props =>
<div>
{currentUser.isAuthenticated == true ?
<PostForm {...props}/> : <Redirect to='/login' />
}
</div>
}