如何在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);

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

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

您需要将常量onAuth = (values.username, values.password)替换为props.onAuth(values.username, values.password)

我们在mapDispatchToPropsmapStateToProps中定义的任何参数在组件中都称为props

相关内容

  • 没有找到相关文章

最新更新