反应挂钩无法使用动态命名正确更新状态

时间:2020-01-25 16:53:56

标签: javascript reactjs

我有一个react组件,用于向我的服务器发出登录请求。

它在模态中,我正在使用Material UI

 <TextField
            onChange={handleChange}
            autoFocus
            name="email"
            margin="dense"
            id="email"
            label="Email Address"
            type="email"
            fullWidth
          />
           <TextField
           onChange={handleChange}
            autoFocus
            name="password"
            margin="dense"
            id="password"
            label="Password"
            type="password"
            fullWidth
          />

然后我具有此状态以及可以正确设置状态的处理程序。

    const [state, setState] = React.useState({
        email: '',
        password: '',
        valid: false
    })

    const handleChange = (event) =>{
        event.preventDefault()
        console
        setState((state) => ({[event.target.name]: event.target.value, ...state}))
        if(state.email.length !== 0 && state.password.length !== 0){
            setState((state) => ({valid: true, ...state}))
        }
    }

但是,无论何时调用该函数,我都会注销syntheticEvent并获取正确的值,但是随后注销状态时,什么也没有设置。我几乎没有使用带有钩子的完整状态对象的经验,所以我无法真正弄清问题所在。

该函数被调用3次后,我收到此警告

,name属性为null
This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

1 个答案:

答案 0 :(得分:1)

如警告所示,尝试一次更新状态:

const handleChange = event => {
  event.preventDefault();
  const { name, value } = event.target;
  setState(state => {
    const { email, password } = state;
    const valid = email.length !== 0 && password.length !== 0;
    return { [name]: value, valid, ...state };
  });
};