React hooks setState try catch 中的可能错误
React hooks setState possible bug in try catch
我有一个函数来处理登录表单的提交,但发生了一些非常奇怪的事情。
如果我第一次尝试正确输入所有字段,一切正常,但如果我触发错误,那么每次我 运行 函数错误将始终为 true,即使在函数开始时将其设置为 false。
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 });
}
});
};
@Keno Clayton 提供的解决方案有效。
然后我在 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:
您在 setState
挂钩中缺少 state =>
。
setState(state => ({ ...state, error: false, success: false }));
我有一个函数来处理登录表单的提交,但发生了一些非常奇怪的事情。 如果我第一次尝试正确输入所有字段,一切正常,但如果我触发错误,那么每次我 运行 函数错误将始终为 true,即使在函数开始时将其设置为 false。
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 });
}
});
};
@Keno Clayton 提供的解决方案有效。 然后我在 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:
您在 setState
挂钩中缺少 state =>
。
setState(state => ({ ...state, error: false, success: false }));