【问题标题】:ReactNative - get values from redux-formReactNative - 从 redux-form 获取值
【发布时间】:2019-01-15 12:35:12
【问题描述】:

我使用 ReactNative + redux + redux-form。

在我的 login.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 中,我没有找到任何使用 &lt;form&gt; 元素的示例,但它可以工作。

【问题讨论】:

  • 表单提交时是否调用了登录函数?
  • 我会更新我的问题

标签: react-native redux redux-form


【解决方案1】:

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

formValueSelector

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在你的道具中访问它

【讨论】:

  • 谢谢,这就是我在 doc 上看到的原因,但是如何将它与 reducer 结合起来呢?我有一个reducer(loginReducer),在mapStateToProps函数里不知道怎么组合
  • 如果您的 loginReducer 包含 emailpassword 的字段,那么您可以将 mapStateToProps 中的字段合并为 const {email , password} = selector(state, 'email', 'password') 并返回为 loginReducer: {...state.loginReducer, email, password}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
相关资源
最近更新 更多