简体   繁体   中英

Passing in Redux state to React Component

I am using react-redux to have a smoother data flow in my app. In my LoginPage component, I use pure component for simplicity.

const LoginPage = ({ auth, doLogin, doLogout }) => (

    <div>
      <NavBar auth={auth}/>
        <div className="row">
            <div style={{display: 'flex', justifyContent: 'center'}} className="col-md-4 col-md-offset-4">
                <LoginForm auth={auth} doLogin={doLogin} doLogout={doLogout}/>
            </div>
        </div>
      </div>

);

// Connects state to the props of this component
const mapStateToProps = state => ({
  auth: state.auth,
});

// Return a NEW component that is connected to the Store
export default connect(mapStateToProps, { doLogin, doLogout })(LoginPage);

This works perfectly as I intended, but I tried to change the format not to use the pure component because I wanted to do conditional rendering (to show a different component when logged in).

Now it looks as follows:

const LoginComponent = ({ auth, doLogin, doLogout }) => (

    <div>
      <NavBar auth={auth}/>
        <div className="row">
            <div style={{display: 'flex', justifyContent: 'center'}} className="col-md-4 col-md-offset-4">
                <LoginForm auth={auth} doLogin={doLogin} doLogout={doLogout}/>
            </div>
        </div>
      </div>

);

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <LoginComponent/>
        )
    }
}

I changed the LoginPage to LoginComponent and tried to render LoginComponent in the actual React Component.

However, this gives me an error saying that Cannot read property 'isLoggedIn' of undefined . isLoggedIn is an element of auth .

In my first example, I was able to pass in auth by doing const LoginPage = ({ auth, doLogin, doLogout }) , but not sure how to pass in auth when I changed to the second example.

How can I do this?

Pass the props to the stateless, functional component like you would with any other React component. Right now the props are not being passed to LoginComponent , so they will always be undefined .

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <LoginComponent
              auth={this.props.auth}
              doLogin={this.props.doLogin}
              doLogout={this.props.doLogout}
            />
        )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM