簡體   English   中英

將Redux狀態傳遞給React組件

[英]Passing in Redux state to React Component

我正在使用react-redux在我的應用程序中擁有更流暢的數據流。 在我的LoginPage組件中,為簡單起見,我使用純組件。

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);

這可以按我的預期完美地工作,但是我嘗試更改格式以不使用純組件,因為我想進行條件渲染(登錄時顯示其他組件)。

現在看起來如下:

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/>
        )
    }
}

我將LoginPage更改為LoginComponent並嘗試在實際的React Component中呈現LoginComponent

但是,這給我一個錯誤,指出Cannot read property 'isLoggedIn' of undefined isLoggedInauth的元素。

在我的第一個例子,我能夠在通過auth通過做const LoginPage = ({ auth, doLogin, doLogout })但不知道如何在通過auth時,我改變了第二個例子。

我怎樣才能做到這一點?

像將其他任何React組件一樣,將props傳遞給無狀態的功能組件。 現在,這些道具還沒有傳遞給LoginComponent ,因此它們始終是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}
            />
        )
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM