我试图理解为什么 react 钩子表单中的错误对象变为空,即使在设置错误之后也是如此。我在代码沙箱中构建了一个演示,这应该有助于更清楚地解释这一点。
所以我有一个在更改字段后运行的函数:
const onNameChange = async ({ target: { value } }) => {
setValue("name", value);
const valid = await trigger("name");
console.log("valid", valid, "value", value);
if (!valid) {
return;
}
getPokemonDebounced(value);
setShowPokemon(false);
};
运行 getPokemonDebounced
函数:
const getPokemon = async (input) => {
console.log("getPokemon Fn");
try {
const res = await axios.get(`https://pokeapi.co/api/v2/pokemon/${input}`);
console.log(res);
const { data } = res;
if (data) {
setPokemon(data);
setFetchError(null);
}
console.log(res);
} catch (error) {
setPokemon(null);
setFetchError(error);
setError("name", { type: "manual", message: "CUSTOM name error" });
}
};
// why does the errors object temporarily become blank? nothing seems to set it to blank
const getPokemonDebounced = useDebounce(500, getPokemon);
当 API 调用失败时设置错误。但是,我注意到在这种情况下错误对象变为空:
{}
,直到 getPokemonDebounced 运行并且无法获取以设置错误我的问题是为什么在输入另一个字母后,错误对象立即再次变为空 {}
?输入初始乱码后,然后将错误对象设置为包含错误,我看不到它是如何暂时再次变空的。
形式:
<form onSubmit={handleSubmit(onSubmit /*, onError*/)}>
<input
{...register("name", { required: true })}
name="name"
placeholder="Enter a pokemon"
onChange={onNameChange}
/>
<button type="submit" onClick={onSubmit}>
Show Pokemon
</button>
{errors.name && <p>{errors.name.message}</p>}
</form>
感谢您的帮助
答案 0 :(得分:1)
因为在输入更改时,您会再次运行验证并清除所有有效字段上的错误。
const onNameChange = async ({ target: { value } }) => {
setValue("name", value);
const valid = await trigger("name"); // here you trigger validation that will clear the error if the field is valid
console.log("valid", valid, "value", value);
if (!valid) { // if invalid nothing happens
return;
}
getPokemonDebounced(value); // if valid do the call which will set the new error on fail
setShowPokemon(false);
};
如果您使用与输入无关的名称设置错误,它将持续存在。
setError("randomError", { type: "manual", message: "RANDOM name error" });
来自文档 - https://react-hook-form.com/api/useform/seterror/
- This method will not persist the associated input error if the input passes validation.
- An error that is not associated with an input field will be persisted until cleared with clearErrors.