使用Redux和React Native将值传递给action creator

时间:2017-06-29 22:42:46

标签: reactjs react-native redux redux-form

如何将reduxForm字段中的值发送到我的登录actionCreator,以便我可以从那里生成用于身份验证的调度。这是我到目前为止所拥有的。基本上在提交时,我希望使用“表单”中的值调用登录操作创建者

import React, {Component} from 'react';
import {TouchableHighlight,Alert, AsyncStorage,StyleSheet,Text, TextInput, TouchableOpacity, View} from 'react-native';
import {Actions} from 'react-native-router-flux';
import { Field,reduxForm } from 'redux-form'
import { connect } from 'react-redux'

import { login } from '../../actions/user.js'


// const submit = values => {
//    authenticate()
//    //login(values.email, values.password);
// }

const renderInput = ({ input: { onChange, ...restInput }}) => {
  return <TextInput style={styles.input} onChangeText={onChange} {...restInput} />
}

const Authentication = (props) => {
 const { handleSubmit } = props
 const {login} = props

 const {
    container,
    text,
    button,
    buttonText,
    mainContent
  } = styles
  
    return (
       <View style={styles.container}>
          
         <Text>Email:</Text>
         <Field name="email" component={renderInput} />
         
         <Text>Password:</Text>
         <Field  name="password" component={renderInput} />

      <TouchableOpacity onPress={handleSubmit(login)}>
        <Text style={styles.button}>Submit</Text>
      </TouchableOpacity>


      </View>
    );
  
}


function mapStateToProps (state) {
  return {
    userData: state.userData
  }
}

function mapDispatchToProps (dispatch) {
  return {
    login: () => dispatch(login())
  }
}



Authentication = reduxForm({
  form: 'loginForm'  // a unique identifier for this form
})(Authentication)

// You have to connect() to any reducers that you wish to connect to yourself
const AuthenticationComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(Authentication)

export default AuthenticationComponent

1 个答案:

答案 0 :(得分:1)

从redux-form文档中我发现onSubmit将值传递给传递给它的函数。对于此表单,传递的值是JSON对象。将值传递给我的动作创建者的解决方案如下。

在mapDispatchToProps函数中使用变量作为输入公开函数:

function mapDispatchToProps (dispatch) {
  return {
    login: (val) => dispatch(login(val))
  }
}

然后在组件中:

<TouchableOpacity onPress={handleSubmit(login)}>
        <Text style={styles.button}>Submit</Text>
      </TouchableOpacity>

希望这有帮助。