繁体   English   中英

带有对象数组的 ReactNative useState

[英]ReactNative useState with array of objects

我正在构建一个表单字段验证对象。 我使用 useState 来跟踪表单上每个字段中的值和用于验证的字段类型,即电子邮件、文本、密码。 我可以用两个单独的钩子来做到这一点(一个用于值,一个用于状态)。 我试图将它们放在一个对象中。 这就是问题发生的地方。

字段名称是每个字段的键。 该对象如下所示

      fName : {
          text: 'John',
          colType: 'text'
          }

      lName : {
          text: 'Doe',
          colType: 'text'
          }

      hairColor : {
          text: 'Brown'
          colType: 'text'

      birthDate : {
          text: '02/02/2010'
          colType: 'date'

如您所见,验证将基于字段类型。 此验证将在表单的提交时发生。 该组件将可重用于所有表单。 由于这个原因,我正在尝试使其通用。

这是我试图用于 setter 函数的内容

    setValues({...values,
        [name] : {
            text : [text],
            colType : [colType]
            }
    });

我在解构它以获取文本和 colType 以根据 colType 验证文本时遇到问题。 [name] 是要验证的对象的名称。

有任何想法吗?

您正确使用动态键[name] 但是,您正在尝试使用一个项目设置一个数组,变量textcolTypetext : [text]表示将一个对象的 Array 设置为父对象的text字段)。

相反,它应该是:

setValues({...values,
    [name] : {
        text : text,
        colType : colType
    }
});

或者:

setValues({...values,
    [name] : {
        text,
        colType
    }
});

在问题中使用上面的例子:

将值放入 useState 钩子:

const [values, setValues] = useState([]);

setValues({...values,
    [name] : {
        text,
        colType
    }
});

要从 useState 钩子中读取值,包括键:

const entries = Object.entries(values); 

entries.forEach (function (arrayItem) {
    const {text, colType} = values[arrayItem[0]]; // arrayItem[0] = [name] text = text value colType = colType value for the key which is [name]
    ... the rest of the code to validate the entries for all of the columns on the form
})

可能有更好/更易读的方法来提取这些内容,但这是有效的。 如果您有更好的方法,请发布,我很乐意更新我的。 感谢 PJohnson 的帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM