反应useState钩-setState导致多个重新渲染

时间:2020-06-09 04:52:04

标签: javascript reactjs react-hooks jsx

我使用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
};

不是应该只重新渲染一次组件吗?是什么导致第二次重新渲染?

Working demo

0 个答案:

没有答案