使用redux状态重定向React路由器但连接的props是空的

时间:2017-11-12 10:46:29

标签: javascript reactjs redux react-redux react-router-v4

这几乎完全基于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,
})

0 个答案:

没有答案