在storybook和App.tsx中都出现的一个问题
来源:11-17 Form表单总结

慕丝2190735
2023-04-19
Form组件中会出现这么一个错误:
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.org/link/controlled-components
at input
at div
at div
at div
at FormItem (http://localhost:3000/static/js/bundle.js:1882:5)
at div
at form
at http://localhost:3000/static/js/bundle.js:1741:5
at App (http://localhost:3000/static/js/bundle.js:182:61)
这个错误一般是没有初始化值(比如undefined)之后赋值之后提示的,是受控组件的问题。不过我排查了一下,在使用checkbox和select组件的时候就出现了这个问题。我尝试过给这两个组件赋默认值,但是没有作用。并且select组件中,单独拿出来设置defaultValue是可以的,在Form组件里面就不行了,而且我尝试console.log打印defaultValue的时候发现它的值是由undefined转变为空字符串,并没有我预设的值。此外在storybook里面也有这个错误,但是它可以渲染initialValue,只是不能设置重置按钮,但是放在App.tsx里面不仅不能显示initialValue并且也不能设置App.tsx。
另外还有一个在test里面发现的问题,jest目前不能处理ESmodule,所以之前的测试中高版本的axios根本没法使用,这个好解决,只要安装低版本的axios就可以了,然后lodash-es就不能安装低版本了,jest不能识别lodash-es,只能安装lodash来使用,请问老师有什么解决办法吗?
项目源代码在 https://github.com/carbonium14/components-library
1回答
-
张轩
2023-04-20
同学你好
第一个问题:
请问你使用的原生的 checkbox 和 select 的组件吗?除了这个警告之外还可以正常的运行吗?
第二个问题:在 Jest 中使用新版 axios 和 lodash-es 可能会出现一些问题,因为它们使用了 ES6 模块语法,而 Jest 默认使用的是 CommonJS 模块语法。这可能会导致一些模块加载和解析的问题,例如:无法正确加载模块、无法正确解析模块的导出等。
可以使用 transformIgnorePatterns 这个参数来忽略对应的转换,就可以了。在 jest.config.js 中
// jest.config.js module.exports = { // 忽略转换 transformIgnorePatterns: [ '/node_modules/(?!lodash-es|axios)' ], };
022023-04-21
相似问题