ReactNative - 从 redux-form 获取值



我使用 ReactNative + redux + redux-form。

在我的登录.js屏幕中,我有这个:

function bindAction(dispatch) {
    return {
        actions: bindActionCreators(loginActions, dispatch)
    };
}
function mapStateToProps(state) {
    return state.loginReducer
}
export default connect(mapStateToProps, bindAction)(reduxForm({
    form: "login",
    initialValues: {
        email: "test@test.fr",
        password: "123123"
    }
})(LoginForm));

我的形式是:

<Field
    name="email"
    component={this.renderInput}
    type="email"
    validate={[email, required]}
/>
<Field
    name="password"
    component={this.renderInput}
    type="password"
    validate={[minLength6, maxLength15, required]}
/>

我想用我的字段的值调用函数login()

我试过了:

login() {
    if (this.props.valid) {
        this.props.actions.loginUser(selector(this.state, 'email', 'password'));
    }
}

跟:

const selector = formValueSelector("login")

我没有错误,但我的字段在login()函数中总是空的。

老实说,我阅读了文档,但我不确定如何使用正确的 redux-form。我需要使用其他东西来获取字段值?谢谢。

**

编辑 **

关于一些例子,我现在使用以下代码:

<Button
    style={styles.loginBtn}
    disabled={this.props.loading}
    onPress={handleSubmit(this.login)}
>
...
</Button>

现在,我可以在我的函数中访问表单数据:

login(data) {
    if (this.props.valid) {
        this.props.actions.loginUser({
            username: data.email, 
            password: data.password
        });
         ....

我不知道这是否是正确的方法,在 react-native 中,我没有找到任何使用 <form> 元素的示例,但它有效。

在 redux-form 中,您可以使用 handleSubmit 函数将值传递给表单有效的处理程序,也可以使用 formValueSelector 获取表单

句柄提交

<Button
    style={styles.loginBtn}
    disabled={loading || !valid || pristine}
    onPress={handleSubmit(this.login)}
>
...
</Button>
login(data) {
  this.props.actions.loginUser({
    username: data.email,
    password: data.password
  });
}

表单值选择器

const LoginForm = reduxForm({ // <== const Form Handler
  form: 'login', // <== Your Redux Form name
  initialValues: {
    email: "test@test.fr",
    password: "123123"
  }
})(Login); // <== Bind your Class Name here
const selector = formValueSelector('login') // <== Redux Form Name
const mapStateToProps = (state) => ({
  email: selector(state, 'email'),
  password: selector(state, 'password'),
});
export default connect(mapStateToProps)(LoginForm); // <== Bind the const Form Handler

然后通过const {email, password} = this.props在您的道具中访问它

最新更新