首页 文章

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

提问于
浏览
6

请原谅潜在的noob问题,我是新的反应和反应 - 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')); 行中,我希望将真实的电子邮件和密码作为有效负载提交 . 但我不是't understand how I should be accessing it from the component (i.e. I can'只是使用 this.props.login )或者我是否应该从商店访问它(我将在哪里通过商店?)

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

1 回答

  • 6

    我认为这可以通过两种方式处理 . mapDispatchToProps作为react-redux连接函数的第二个参数传递 . 它为连接的组件提供对某些操作创建者的访问权限 . 在这种情况下,你给它的动作创建者 onLoginClickonEmailUpdateonPAsswordUpdate .

    现在可以通过 this.props.onLoginClickthis.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>  
    }
    

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

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

相关问题