[英]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
。 isLoggedIn
是auth
的元素。
在我的第一個例子,我能夠在通過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.