正文从这开始~

总览

当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled input to be controlled"警告。为了解决该问题,将input的值初始化为空字符串。比如说,value={message || ''} 。

这里有个例子来展示错误是如何发生的。

import {useState} from 'react';

const App = () => {
// ️ didn't provide an initial value for message
const [message, setMessage] = useState(); const handleChange = event => {
setMessage(event.target.value);
}; return (
<div>
<input
type="text"
id="message"
name="message"
onChange={handleChange}
value={message}
/>
</div>
);
}; export default App;

上面代码的问题在于,message变量被初始化为undefined,因为我们没有在useState钩子中为其传递初始值。

备用值

解决该错误的一种方式是,如果input的值为undefined,那么就提供一个备用值。

import {useState} from 'react';

const App = () => {
const [message, setMessage] = useState(); const handleChange = event => {
setMessage(event.target.value);
}; // ️ value={message || ''} return (
<div>
<input
type="text"
id="message"
name="message"
onChange={handleChange}
value={message || ''}
/>
</div>
);
}; export default App;

我们使用逻辑与(||)操作符,如果操作符左侧的为假值(比如说undefined),则返回其右侧的值。

如果message变量的值存储为undefined,我们将空字符串作为备用值进行返回。

useState

另一种解决方案是,在useState钩子中为state变量传递初始值。

import {useState} from 'react';

const App = () => {
// ️ pass an initial value to the useState hook
const [message, setMessage] = useState(''); const handleChange = event => {
setMessage(event.target.value);
}; return (
<div>
<input
type="text"
id="message"
name="message"
onChange={handleChange}
value={message}
/>
</div>
);
}; export default App;

在useState钩子中传递初始值可以避免警告,因为此时message变量并没有从undefined变更为一个值。

引起警告的原因是,当message变量在没有值的情况下被初始化时,它会被设置为undefined。

传递一个像value={undefined}这样的属性,就等于根本没有传递value属性。

一旦用户在input中开始输入,value属性就会被传递到input表单,输入就会从不受控变为受控,这是不被允许的。

defaultValue

注意,如果你使用一个不受控制的input表单,你应该使用defaultValue属性而不是value。

import {useRef} from 'react';

const App = () => {
const inputRef = useRef(null); function handleClick() {
console.log(inputRef.current.value);
} return (
<div>
<input
ref={inputRef}
type="text"
id="message"
name="message"
defaultValue="Initial value"
/> <button onClick={handleClick}>Log message</button>
</div>
);
}; export default App;

上述示例使用了不受控制的input。注意input表单上并没有设置onChange或者value属性。

你可以使用defaultValue属性来为不受控制的input传递初始值。然而,这一步骤不是必要的,如果你不想设置初始值,你可以省略该属性。

当使用不受控制的input表单时,我们使用ref来访问input元素。每当用户点击例子中的按钮时,不受控制的input 的值都会被记录下来。

你不应该为不受控制的input设置value属性,因为这将使input表单不可变,你将无法在其中输入。

React报错之react component changing uncontrolled input的更多相关文章

  1. React报错之React hook 'useState' cannot be called in a class component

    正文从这开始~ 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class compo ...

  2. React报错之React Hook useEffect has a missing dependency

    正文从这开始~ 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing depende ...

  3. React报错之React hook 'useState' is called conditionally

    正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...

  4. React报错之React Hook 'useEffect' is called in function

    正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...

  5. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  6. npm install 报错 error Unexpected end of JSON input while parsing near '...sShrinkwrap":false,"d' 解决办法

    npm install 报错 : error Unexpected end of JSON input while parsing near '...sShrinkwrap":false,& ...

  7. SpringBoot整合Swagger2案例,以及报错:java.lang.NumberFormatException: For input string: ""原因和解决办法

    原文链接:https://blog.csdn.net/weixin_43724369/article/details/89341949 SpringBoot整合Swagger2案例 先说SpringB ...

  8. React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,

    今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ...

  9. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

随机推荐

  1. Python 微博搜索爬虫

    微博搜索爬虫 网页分析 由于网页端反爬虫机制比较完善所以才去移动端进行爬虫. url地址:https://m.weibo.cn/ 搜索框,输入关键词进行搜索 对网页进行抓包,找到相关数据 查看数据是否 ...

  2. LC T668笔记 & 有关二分查找、第K小数、BFPRT算法

    LC T668笔记 [涉及知识:二分查找.第K小数.BFPRT算法] [以下内容仅为本人在做题学习中的所感所想,本人水平有限目前尚处学习阶段,如有错误及不妥之处还请各位大佬指正,请谅解,谢谢!] !! ...

  3. ShardingSphere-proxy-5.0.0部署之分表实现(一)

    一.说明 环境准备:JDK8+     mysql 5.x 官网:https://shardingsphere.apache.org/ 下载地址:https://archive.apache.org/ ...

  4. VMware 虚拟机安装CentOS镜像详细步骤

    CentOS目前官网提供的下载版本有6.7.8,最新的版本为8,不过个人推荐CentOS 7 的版本,因为相比较于最新版本,版本7更加地稳定.而相比于版本6,版本7新增了很多的功能.CentOS 7 ...

  5. [pwn基础] Linux安全机制

    目录 [pwn基础] Linux安全机制 Canary(栈溢出保护) 开启关闭Cannary Canary的种类 Terminator canaries(终结者金丝雀) Random cannarie ...

  6. ruoyi接口权限校验

    此文章属于ruoyi项目实战系列 ruoyi系统在前端主要通过权限字符包含与否来动态显示目录和按钮.为了防止通过http请求绕过权限限制,后端接口也需要进行相关权限设计. @PreAuthorize使 ...

  7. SAP Display picture

    program sap_picture_demo. set screen 200. TYPE-POOLS cndp. ***************************************** ...

  8. uipath 如何利用函数split切割换行符?

    uipath 如何利用函数split切割换行符? 答案在这 https://rpazj.com/thread-178-1-1.html

  9. MySQL case when then 用法

    下面演示一下MYSQL中的CASE WHEN THEN的用法. 一. SELECT MENU_NAME, YXBZ, case YXBZ when 'Y' then '开放' when 'N' the ...

  10. Pytorch从0开始实现YOLO V3指南 part4——置信度阈值和非极大值抑制

    本节翻译自:https://blog.paperspace.com/how-to-implement-a-yolo-v3-object-detector-from-scratch-in-pytorch ...