[英]Please tell me why this expression doesn't work
React code:反应代码:
const [state, setState] = useState({login:'', password: ''});
const changeHandler = (e) =>{
setState({[e.target.name]: e.target.value});
}
return(
<div className='login-wrapper'>
<form onSubmit={(e) => submitHandler(e)}>
<Input color='primary'
margin='dense'
placeholder='login'
type='text'
style={{margin:'20px', width:'300px'}}
name='login'
value={state.login}
onChange={(e) => changeHandler(e)}/>
</form>
</div>)}
Error:错误:
A component is changing a controlled input of type password to be uncontrolled.一个组件正在将密码类型的受控输入更改为不受控。 Input elements should not switch from controlled to uncontrolled (or vice versa).输入元素不应从受控切换到不受控(反之亦然)。 Decide between using a controlled or uncontrolled input element for the lifetime of the component.决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
e.target.name
is probably coming through as undefined, so value={state.login}
as a prop returns undefined
, which switches the component to non-controlled. e.target.name
可能是未定义的,因此value={state.login}
作为道具返回undefined
,这会将组件切换到非受控状态。
Fix with this:修复这个:
const loginChangeHandler = (e) => setState({...state, login: e.target.value});
From the docs on useState
:来自useState
的文档:
Unlike this.setState in a class, updating a state variable always replaces it instead of merging it.与 class 中的 this.setState 不同,更新 state 变量总是替换它而不是合并它。
If you use an object as the value of a useState
hook, an update to it must replace all values.如果您使用 object 作为useState
挂钩的值,则对其的更新必须替换所有值。
What is happening is you are updating login
, but not replacing password
.发生的事情是您正在更新login
,但没有替换password
。 So the password input is presumably the one throwing the warning.所以密码输入大概是引发警告的那个。 The password was set to a string, then it becomes undefined
.密码设置为字符串,然后变为undefined
。
The solution is simple, spread the previous state values into the new object before updating it:解决方案很简单,在更新之前将之前的 state 值传播到新的 object 中:
setState({...state, [e.target.name]: e.target.value});
The most optimal change handler would also take advantage of the functional form of the updater and look something like this:最优化的更改处理程序也将利用更新程序的功能形式,看起来像这样:
// Destructure the event for cleaner syntax and avoiding the pitfall of pooled events
const changeHandler = ({ target: {name, value} }) => {
// Use a functional update to ensure we always have the most recent copy of state
setState(prev => ({ ...prev, [name]: value }));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.