【问题标题】:How to pass data from Form to mapDispatchToProps in React如何在 React 中将数据从 Form 传递到 mapDispatchToProps
【发布时间】:2020-05-03 12:41:38
【问题描述】:

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

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

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

这里是sn-p的代码:

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);

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      我们在mapDispatchToPropsmapStateToProps 中定义的任何参数都在组件中以props 的形式出现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-03
        • 2018-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多