这几乎完全基于React-router基本身份验证示例。唯一的区别是用户数据来自带有mapStateToProps
的redux。那么为什么最初的this.props.isLoggedIn
只是空的?
const PrivateRoute = ({ component: Component, userLoggedIn, ...rest }) => (
<Route {...rest} render={props => (
userLoggedIn ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
class App extends Component {
componentWillMount () {
console.log(this.props.isLoggedIn) // getting correct value
}
render () {
return (
<Router>
<div>
{this.props.isLoggedIn} // <============= EMPTY :(
<Route exact path="/" render={() => (
!this.props.isLoggedIn ? (
<Redirect to="/login"/>
) : (
<Redirect to="/studio"/>
)
)}/>
<Route path="/login" component={Login}/>
<PrivateRoute
path="/studio"
component={Studio}
userLoggedIn={this.props.isLoggedIn}
/>
</div>
</Router>
)
}
}
const mapStateToProps = state => ({
isLoggedIn: state.user.isLoggedIn,
})