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

React中能否在map函数内部嵌套使用map以渲染字段对应类型

解决方案

你不需要嵌套map,也不需要额外调用API接口,类型数据已经存在TypeForm这个state中,且FieldForm和TypeForm的数组索引是一一对应的,直接用map遍历的索引取值即可。

修改后的代码示例

const FormScreen = ({route}) => {
  const [FieldForm, setFieldForm] = useState([]);
  const [TypeForm, setTypeForm] = useState([]);

  useEffect(() => {
    // 按原有逻辑调整判断条件,避免重复赋值
    if (FieldForm.length > 0) {
      return;
    }
    const paramData = JSON.parse(route.params.paramKey);
    setFieldForm(paramData.fields);
    setTypeForm(paramData.type);
  },[route.params.paramKey]); // 依赖调整为路由参数,避免死循环
   
  return (
    <SafeAreaView style={{flex: 1}}>
      <View>
        <Text>COLLECTION :</Text>

        {FieldForm.length > 0 ? (
          FieldForm.map((item, index) => {
            // 取对应索引的字段类型
            const fieldType = TypeForm[index];
            return (
              <View key={item}> {/* 优先用字段名做key,不要每次生成新的uuid */}
                <Text>{item} *({fieldType})*</Text>
                {/* 可根据类型做条件渲染,示例如下
                {fieldType === 'Date' ? <DatePicker /> : <TextInput />}
                */}
              </View>
            )
          })
        ) : (
          <Text> Loading ...</Text>
        )}

      </View>
    </SafeAreaView>
  );
};

优化提醒

  • 原有代码中用uuid.v4()作为key会导致每次渲染key都变化,触发不必要的组件重绘,优先用唯一的字段名作为key,没有唯一值再用索引
  • useEffect的原有依赖包含TypeForm会触发死循环:effect内部修改了TypeForm,会触发依赖变化重新执行effect,调整为只依赖路由参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:57:03