我使用React 16.13.1创建了一个非常简单的表单,其中只有2个字段:
<div>
<form onSubmit={handleSubmit}>
<div>
<label>Username</label>
<input name="username" onChange={handleInputChange} value={credentials.username} />
</div>
<div>
<label>Password</label>
<input type="password" name="password" onChange={handleInputChange} value={credentials.password} />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>
</div>
我正在使用通用函数来处理输入更改事件:
const [credentials, setCredentials] = useState({});
const handleInputChange = event => {
const { name, value } = event.target;
setCredentials({ ...credentials, [name]: value }); // <<< This line is causing the component to re-render twice on every key typed in any field
};
不是应该只重新渲染一次组件吗?是什么导致第二次重新渲染?