简体   繁体   English

反应挂钩setState尝试捕获中可能的错误

[英]React hooks setState possible bug in try catch

I have a function to handle the submission of a login form and something really strange is happening. 我有一个处理登录表单提交的功能,确实发生了一些奇怪的事情。 If I enter all the field correctly at the first try everything works fine but if I trigger an error then every time that I run the function error will always be true even setting it as false in the start of the function. 如果我第一次正确输入所有字段,那么一切都会正常,但是如果我触发一个错误,那么每次运行该函数时,即使在函数启动时将其设置为false,错误也会始终为true。

const initialState = {
email: '',
password: '',
error: false,
success: false
};
const [state, setState] = useState(initialState);

const handleSubmit = e => {
e.preventDefault();
setState({ ...state, error: false, success: false });

props.form.validateFields(async (err, values) => {
  try {
    const { data, status } = await axios.post(vManager.path, values);

    if (data.token) {
      localStorage.setItem('token', data.token);
    }

    setState({ ...state, success: true });
  } catch (err) {
    setState({ ...state, error: true });
  }
});

}; };

You were missing a state => inside the setState hook. 您在setState挂钩中缺少state =>

setState(state => ({ ...state, error: false, success: false }));

Reference 参考

The solution presented by @Keno Clayton works. @Keno Clayton提出的解决方案起作用。 And then I found the explanation on React documentation 然后我在React文档中找到了解释

state is a reference to the component state at the time the change is being applied. 状态是在应用更改时对组件状态的引用。 It should not be directly mutated. 它不应该直接突变。 Instead, changes should be represented by building a new object based on the input from state and props. 相反,更改应通过根据状态和道具的输入来构建新对象来表示。 For instance, suppose we wanted to increment a value in state by props.step: 例如,假设我们想通过props.step增加state的值:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM