如何在 Redux 调度中访问表单值?

How to access a form value in Redux dispatch?

我有以下表单组件:

export class LoginPage extends React.PureComponent {
  render() {
    return (
      <div>
        <Form onSubmit={this.props.onSubmitForm}>
          <Input id="username" type="text" value={this.props.username} />
          <button type="submit">Submit</button>
        </Form>
      </div>
    );
  }
}

在组件之后我有一个 mapDispatchToProps 函数:

export function mapDispatchToProps(dispatch) {
  return {
    onSubmitForm: (evt) => {
      // I need to access the `username` property here to pass it as argument.
      dispatch(postUsername(username));
    },
  };
}

我需要访问 mapDispatchToProps 函数中的 username。 最简单的方法是什么?我不需要在此步骤中存储 username
谢谢。

您可以使用 event.target.username.value 属性,因此您的代码应如下所示:

export function mapDispatchToProps(dispatch) {
  return {
    onSubmitForm: (evt) => {
      // I need to access the `username` property here to pass it as argument.
      dispatch(postUsername(evt.target.username.value));
    },
  };
}

通过这样做,您应该拥有用户名值。