首页 > 解决方案 > 如何在 React 中将数据从 Form 传递到 mapDispatchToProps

问题描述

我是新手,试图构建一个登录表单,能够从表单中提取用户名和密码。但是我在尝试将其传递给 mapDispatchToProps 以将其分派到后端时遇到了麻烦。

我将如何从“值”获取用户名和密码以实际将其传递给 mapDispatchToProps?

我收到一条错误消息,提示无法在函数外部访问“onAuth”。

这是代码片段:

const NormalLoginForm = (props) => {


  const onFinish = values => {
    const onAuth = (values.username, values.password) // This is where the error is occuring
    console.log('Success:', values);
  };

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  return (
  
        <Form
            {...layout}
            name="basic"
            initialValues={{
                remember: true,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            >
            <Form.Item
                label="Username"
                name="username"
                rules={[
                {
                    required: true,
                    message: 'Please input your username!',
                },
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="Password"
                name="password"
                rules={[
                {
                    required: true,
                    message: 'Please input your password!',
                },
                ]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit">
                 Submit
                </Button>
                <NavLink 
                    style={{marginRight: '10px'}}
                    to='/signup/'> Signup
                </NavLink>

            </Form.Item>
        </Form>
  );
};



const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);

标签: javascriptreactjsreact-redux

解决方案


看起来 mapDispatchToProps 已经正确设置,您只需要调用它创建的函数。

const onFinish = values => {
  props.onAuth(values.username, values.password);
}

推荐阅读