【发布时间】:2024-05-19 04:25:02
【问题描述】:
我想创建一个表单来编辑使用配置文件。该表单呈现来自user 对象的数据。我想使用 React 的 useState Hook 来保存表单的状态,并且我想保留一个对象来使用处理整个用户对象更改的 onChange 函数来跟踪表单的更改。为什么这不起作用?
function Profile() {
const [user, setUser] = useState({});
const [errors, setErrors] = useState({});
useEffect(() => {
axios.get(`/api/v1/users/me`)
.then(res => setUser(res.data.user))
}, [])
const onChange = e => {
user[e.target.name] = e.target.value;
setUser(user)
}
return (
< div >
<form onSubmit={null}>
<div className="form-group">
<label htmlFor={user.name}>Name</label>
<input type="text" name="name"
className={`form-control form-control-lg ${errors.name ? 'is-invalid' : ''}`}
onChange={onChange} placeholder="Fred Flintstone" value={user.name || ''}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" name="email"
className={`form-control form-control-lg ${errors.email ? 'is-invalid' : ''}`}
onChange={onChange} placeholder="fred.flintstone@aol.com" value={user.email || ''}
/>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" name="username"
className={`form-control form-control-lg ${errors.username ? 'is-invalid' : ''}`}
onChange={onChange} placeholder="yabadabadu" value={user.username || ''}
/>
</div>
</form>
<div>
<button type="button" className="btn btn-light btn-sm float-right" onClick={() => console.log("Logout")}>Logout</button>
</div>
</div >
)
}
【问题讨论】:
-
user[e.target.name] = e.target.value;这是 React 中的 mutating the current state, which is an anti-pattern。
标签: javascript reactjs react-hooks