React-redux 在 mapDispatchToProps 中获取道具或状态

React-redux get props or state in mapDispatchToProps

请原谅潜在的菜鸟问题,我是 React 和 React-redux 的新手。

我目前有一个代表登录屏幕的组件。它的一个道具是 "login",一个包含电子邮件和密码的字典。定义组件后,我使用 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)),
  };
};

显然,在行 dispatch(actions.submitLogin('testuser', 'testpw')); 中,我希望将真实的电子邮件和密码作为有效负载与操作一起提交。但我不明白我应该如何从组件访问它(即我不能只使用 this.props.login)或 if/how 我应该从商店访问它(我会在哪里通过商店在?)

任何澄清都将非常有帮助!

我认为这可以通过两种方式处理。 mapDispatchToProps 作为第二个参数传递给 react-redux connect 函数。它使连接的组件可以访问某些动作创建者。在本例中,您为其指定动作创建者 onLoginClickonEmailUpdateonPAsswordUpdate.

这些功能现在可以通过 this.props.onLoginClickthis.props.onEmailUpdate 等在您的组件中访问。一个简单的解决方案是在您的登录按钮上创建一个 onClick 事件,或者 onSubmit 的登录表单。如果你在你的 redux state 上更新你的 Email 和 Password 并将它们作为 props 传递给这个组件,你可以这样做:

在您的登录中class:

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

并更新 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)),
};

选项 2

否则,根据此处的 react-redux 文档 https://github.com/reactjs/react-redux/blob/master/docs/api.md,您还可以使用 mapDispatchToPropsownProps.

的第二个参数

因此您可以将 onLoginClick 更改为如下所示:

onLoginClick: () => {
  const email = ownProps.email;
  const password = ownProps.password;

  dispatch(actions.submitLogin(email, password));
  dispatch(actions.changeRootNav(rootNavs.OVERVIEW_NAV))
}

在您的表单上,您可以这样做:

render() {
  <form onSubmit={this.props.onLoginClick}>
      ...
  </form>  

}

或者,如果您希望它只出现在单击按钮上...

<button onClick={this.props.onLoginClick}>Login</button>