调试 React 用法

以下是您可能在控制台中看到的一些常见错误以及如何修复它们。

将不受控输入更改为受控输入

如果您在控制台中看到此错误

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.ac.cn/link/controlled-components
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.ac.cn/link/controlled-components

很可能您忘记了 defaultValues 在您的 useForm Hook 或 form.Field 组件用法中。发生这种情况是因为在表单值初始化之前渲染了输入,因此当进行文本输入时,从 undefined 更改为 ""

字段值类型为 unknown

如果您正在使用 form.Field,并且在检查 field.state.value 的值时,您看到字段的值类型为 unknown,则很可能是您的表单类型对于我们安全评估而言太大了。

这通常表明您应该将表单分解为更小的表单,或者为您的表单使用更具体的类型。

解决此问题的一种方法是使用 TypeScript 的 as 关键字来强制转换 field.state.value

tsx
const value = field.state.value as string
const value = field.state.value as string

类型实例化过于深入,可能无限

如果您在运行 tsc 时在控制台中看到此错误

Type instantiation is excessively deep and possibly infinite
Type instantiation is excessively deep and possibly infinite

您遇到了我们在类型定义中没有捕获到的错误。虽然我们已尽力确保我们的类型尽可能准确,但在某些边缘情况下,TypeScript 在处理我们类型的复杂性时遇到了困难。

在 GitHub 上向我们报告此问题,以便我们修复它。只需确保包含最小的重现,以便我们能够帮助您调试。

请记住,此错误是 TypeScript 错误,而不是运行时错误。这意味着您的代码仍将在用户的机器上按预期运行。

订阅 Bytes

您每周的 JavaScript 新闻。每周一免费发送给超过 100,000 名开发者。

Bytes

没有垃圾邮件。随时取消订阅。