bai*_*ang 6 reactjs redux react-redux
请原谅潜在的noob问题,我是新的反应和反应 - redux.
我有一个代表当前登录屏幕的组件.它的一个道具是"登录",一个包含电子邮件和密码的字典.定义组件后,我使用react-redux库将其与商店连接,如下所示:
const mapStateToProps = (state) => {
return {
rootNav: state.rootNav,
login: state.login,
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onLoginClick: () => {
// TODO: actually get the login credentials from the view
dispatch(actions.submitLogin('testuser', 'testpw'));
dispatch(actions.changeRootNav(rootNavs.OVERVIEW_NAV))
},
onEmailUpdate: (email) => dispatch(actions.updateEmail(email)),
onPasswordUpdate: (password) => dispatch(actions.updatePassword(password)),
};
};
Run Code Online (Sandbox Code Playgroud)
显然,在这行中dispatch(actions.submitLogin('testuser', 'testpw'));我希望将真实的电子邮件和密码作为有效负载提交给动作.但我不明白我应该如何从组件中访问它(即我不能只使用this.props.login)或者是否应该从商店访问它(我将在哪里通过商店?)
任何澄清都会非常有帮助!
我认为这可以通过两种方式处理.mapDispatchToProps作为react-redux连接函数的第二个参数传递.它为连接的组件提供对某些操作创建者的访问权限.在这种情况下,你给它的创造者的行动onLoginClick,onEmailUpdate和onPAsswordUpdate.
这些功能都可以通过在你的组件现在可以访问this.props.onLoginClick,this.props.onEmailUpdate等等.一个简单的方法是创建一个onClick在你的登录按钮事件,或onSubmit登录表单.如果您正在更新您的redux状态的电子邮件和密码并将它们作为道具传递给此组件,您可以执行以下操作:
在您的登录类中:
login() {
// get password and email from the props
const pw = this.props.password;
const email = this.props.email;
// submit login action with email and password
this.props.onLoginClick(email, password)
}
render() {
<form onSubmit={this.login.bind(this)}>
...
</form>
}
Run Code Online (Sandbox Code Playgroud)
并更新mapDispatchToProps以使onLoginClick期望电子邮件和密码.
const mapDispatchToProps = (dispatch, ownProps) => {
return {
// update this action creator to take an email and password
onLoginClick: (email, password) => {
// TODO: actually get the login credentials from the view
dispatch(actions.submitLogin(email, password));
dispatch(actions.changeRootNav(rootNavs.OVERVIEW_NAV))
},
onEmailUpdate: (email) => dispatch(actions.updateEmail(email)),
onPasswordUpdate: (password) => dispatch(actions.updatePassword(password)),
};
Run Code Online (Sandbox Code Playgroud)
选项2
否则根据react-redux docs https://github.com/reactjs/react-redux/blob/master/docs/api.md你也可以使用mapDispatchToProps,ownProps.的第二个参数.
所以你可以改成onLoginClick这样:
onLoginClick: () => {
const email = ownProps.email;
const password = ownProps.password;
dispatch(actions.submitLogin(email, password));
dispatch(actions.changeRootNav(rootNavs.OVERVIEW_NAV))
}
Run Code Online (Sandbox Code Playgroud)
在您的表单上,您可以这样做:
render() {
<form onSubmit={this.props.onLoginClick}>
...
</form>
Run Code Online (Sandbox Code Playgroud)
}
或者如果您希望它仅在按钮上单击...
<button onClick={this.props.onLoginClick}>Login</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5802 次 |
| 最近记录: |