You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中调用Redux Form提交函数返回空数组问题咨询

解决React Native Redux Form提交返回空数组的问题

兄弟,我一眼就瞅出来你这问题出在哪了——你的表单输入字段根本没和Redux Form的状态绑定上,所以提交的时候自然拿不到值,返回空数组。别慌,我给你一步步改好:

核心问题:Input未绑定Redux Form的input对象

Redux Form的Field组件会自动给你传递一个input对象,里面包含了value、onChange这些关键方法,用来同步输入值到Redux的store里。你之前的renderField完全没用到这个对象,导致输入的内容根本没被捕获。

修正步骤

1. 改造renderField函数

把input参数加进去,然后把Input的value和onChangeText绑定到input对象的对应属性上:

const renderField = ({ label, keyboardType, name, icon, iconType, input }) => {
  return (
    <View style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 10 }}>
      {icon && <Icon name={icon} type={iconType} style={{ marginRight: 10 }} />}
      <Input
        label={label}
        keyboardType={keyboardType}
        value={input.value} // 绑定Redux Form维护的字段值
        onChangeText={input.onChange} // 绑定变更事件,同步值到Redux store
        placeholder={`Enter ${label}`}
        style={{ flex: 1 }}
      />
    </View>
  );
};

2. 确保reduxForm装饰器与提交逻辑正确

给你的表单组件加上reduxForm装饰器,指定唯一的表单名称,同时用Redux Form提供的handleSubmit来触发提交:

class YourForm extends Component {
  // 自定义提交处理函数,values会自动传入所有表单字段值
  handleSubmit = (values) => {
    console.log('提交的表单值:', values);
    // 这里写你的API提交逻辑
  };

  render() {
    const { handleSubmit } = this.props; // 从Redux Form的props中获取handleSubmit
    return (
      <View style={{ padding: 20 }}>
        <Field
          name="username" // 唯一字段名,对应values里的key
          component={renderField}
          label="Username"
          icon="user"
          iconType="font-awesome"
        />
        <Field
          name="email"
          component={renderField}
          label="Email"
          keyboardType="email-address"
          icon="envelope"
          iconType="font-awesome"
        />
        <Button
          title="提交"
          onPress={handleSubmit(this.handleSubmit)} // 用Redux Form的handleSubmit包裹自定义处理函数
          style={{ marginTop: 20 }}
        />
      </View>
    );
  }
}

// 配置reduxForm,指定唯一的表单名称
export default reduxForm({
  form: 'loginForm' // 换成你自己的表单名称,必须唯一
})(YourForm);

3. 关键注意点

  • 每个Field的name属性必须唯一,这个名称就是提交时values对象里的键名
  • 必须使用Redux Form提供的handleSubmit触发提交,它会自动收集所有Field的值并传递给你的处理函数
  • 确保你的Redux store已经正确集成了Redux Form的reducer(比如在rootReducer里加上form: formReducer)

验证

修改完之后,再点击提交,你应该就能在控制台看到完整的表单值了,不会再返回空数组啦!

内容的提问来源于stack exchange,提问作者Pranab V V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:58:59