首页 > 解决方案 > 从 API 性能反应动态形式

问题描述

我正在根据 API 返回的内容构建表单。

我建立了字段需要访问的状态,然后存储这个函数的返回,它返回一个字段数组,在状态

  const CreateMainFields = (
    fd = fields,
    currSection = "default",
    f = form,
    sf = setForm
  ) => {
    return fd.map(itm => {
      if (itm.type === "section") {
        return (
          <section key={`section_${itm.id}`}>
            <Typography id={`section_${itm.id}`} variant="h6">
              {itm.label}
            </Typography>
            {CreateMainFields(itm.fields, itm.id)}
          </section>
        );
      } else if (itm.type === "field") {
        console.log(f, f[itm.formValue]);
        return (
          <TextField
            label={itm.label}
            value={f[itm.formValue]}
            onChange={e => {
              const value = e.currentTarget.value;
              sf(old => ({ ...old, [itm.formValue]: value }));
            }}
            key={`field_${itm.formValue}`}
            variant="filled"
          />
        );
      }
      return null;
    });
  };



//Create the fields once the form state is ready
  useEffect(() => {
    if (form && formListReady.current) setContent(CreateMainFields(fields));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form]);

根据变量动态构建表单,无论是从 redux 还是 state,都很容易,我遇到的问题是如何以不影响性能的方式这样做。表单可以很丰富,因为每次用户键入时我都会在状态上存储表单数据,因此我会重新渲染整个内容。

这是一个代码框:https ://codesandbox.io/s/react-dyanmic-form-35uqr?file=/src/Visits.js

除了保持表单大小尽可能短之外,我还能做些什么改进?

标签: reactjsformsperformance

解决方案


推荐阅读