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

React Native中使用Fetch()提交多用户输入:状态保存与POST实现

解决动态表单输入状态保存与POST提交问题

我来帮你梳理下解决方案,你现在的核心问题是没有正确跟踪每个动态生成输入框的状态,导致提交时无法准确获取对应的值。下面是具体的修改步骤和代码示例:

1. 用组件State管理输入状态

首先在组件的构造函数里初始化一个state,用来存储每个文档下的所有输入值,结构设计成按文档标识分组,方便后续区分不同文档的输入:

constructor(props) {
  super(props);
  this.state = {
    // 结构:{ 文档名称/唯一标识: { 字段标题: 输入值, ... }, ... }
    documentInputs: {}
  };
}

2. 修改输入框的渲染逻辑,绑定状态更新

在renderTextandInputs方法里,给每个TextInput绑定对应的文档标识和字段标题,让输入变化时更新state里对应的值,同时给每个输入框设置当前的value,保证输入状态能正确回显:

renderTextandInputs = (obje) => {
  const keyvalue_to_json = JSON.parse(obje.keyValues);
  const textinputName = [];
  const foundTextFields = [];

  for (let i = 0; i < keyvalue_to_json.inputFields.length; i++) {
    const field = keyvalue_to_json.inputFields[i];
    if (field.type === 'textfield') {
      // 生成唯一的key,用来区分不同文档下的不同输入框
      const inputKey = `${obje.name}_${field.title}`;
      // 从state中获取当前字段的输入值,没有则为空字符串
      const currentValue = this.state.documentInputs[obje.name]?.[field.title] || '';

      foundTextFields.push(
        <TextInput
          key={inputKey}
          onChangeText={(text) => this.updateInputValue(obje.name, field.title, text)}
          value={currentValue}
          style={{ borderWidth: 1 }}
          placeholder={field.placeholderText}
        />
      );
      textinputName.push(<Text key={inputKey}>{field.title}</Text>);
    }
  }

  return (
    <View>
      <ListItem 
        title={obje.name} 
        subtitle={obje.description} 
        onPress={() => this.postToBmp(obje)} 
      />
      <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
        <View style={{ flex: 1}}>{textinputName}</View>
        <View style={{ flex: 1}}>{foundTextFields}</View>
      </View>
    </View>
  );
}

3. 添加状态更新方法

新增一个updateInputValue方法,用来安全地更新state中的输入值,避免直接修改state:

updateInputValue = (documentName, fieldTitle, text) => {
  this.setState(prevState => ({
    documentInputs: {
      ...prevState.documentInputs,
      [documentName]: {
        // 保留该文档下已有的其他输入值
        ...prevState.documentInputs[documentName],
        // 更新当前字段的值
        [fieldTitle]: text
      }
    }
  }));
};

4. 修改POST请求逻辑,从State中获取输入值

现在在postToBmp方法里,就可以从state中取出对应文档的所有输入值,填充到请求body里了:

postToBmp = (obje) => {
  // 获取当前文档的所有输入值,没有则为空对象
  const documentInputs = this.state.documentInputs[obje.name] || {};

  // 组装POST请求的参数,注意要和你的字段title对应起来
  const postData = {
    from: 'test@test.dk',
    to: [ 'test test <test2@test2.com>' ],
    attachmentName: obje.name,
    dateString: '19. marts 2019',
    signedByFullName: documentInputs['Full Name'] || '', // 替换成你实际的字段title
    signedByCPRNumber: documentInputs['CPR Number'] || '',
    otherCompanyName: documentInputs['Company Name'] || '',
    otherCompanyCVRNumber: documentInputs['Company CVR'] || ''
  };

  fetch('YOUR_API_URL', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Connection': 'Keep-Alive',
    },
    credentials: 'include',
    body: JSON.stringify(postData)
  })
  .then(response => response.json())
  .then(result => {
    console.log('提交成功:', result);
    // 这里可以添加提交成功后的提示,比如弹出Toast
  })
  .catch(error => {
    console.error('提交失败:', error);
    // 处理错误情况,比如提示用户重试
  });
};

关键说明

  • 为什么用State管理:React Native中组件的状态变化需要通过state来跟踪,这样才能保证输入框的值能正确回显,且提交时能拿到最新的输入内容。
  • 按文档分组:因为你是渲染多个文档的表单,所以需要把每个文档的输入值分开存储,避免不同文档的输入互相覆盖。
  • 字段对应:你需要确保documentInputs中的字段title和POST请求body里的参数名对应起来,比如如果某个输入框的title是"全名",那documentInputs['全名']就对应signedByFullName的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:36:41