gpt4 book ai didi

reactjs - useEffect 未在 react Hook 表单更改时触发

转载 作者:行者123 更新时间:2023-12-02 15:48:04 24 4
gpt4 key购买 nike

希望将 react hook form 与 useEffect 一起使用以实时获取更改(当用户填写表单时),这里没有触发 useEffect 是否有原因,如果有,是否有办法在任何时候触发它表单数据更改?这里的例子来自 https://remotestack.io/react-hook-form-set-update-form-values-with-useeffect-hook/

import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";

export default function SimpleForm() {
const { register, handleSubmit, reset, formState } = useForm();

const [student, initStudent] = useState(null);

useEffect(() => {
setTimeout(
() =>
initStudent({
name: "Little Johnny",
email: "lil@johnny.com",
grade: "3rd",
}),
1200
);
}, []);

useEffect(() => {
console.log("updating.,..");

reset(student);
}, [reset, student]);

function onFormSubmit(dataRes) {
console.log(dataRes);
return false;
}

return (
<div>
<h2 className="mb-3">
React Initiate Form Values in useEffect Hook Example
</h2>

{student && (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="form-group mb-3">
<label>Name</label>
<input
type="text"
name="name"
{...register("name")}
className="form-control"
/>
</div>

<div className="form-group mb-3">
<label>Email</label>
<input
type="email"
name="email"
{...register("email")}
className="form-control"
/>
</div>

<div className="form-group mb-3">
<label>Grade</label>
<input
type="text"
name="grade"
{...register("grade")}
className="form-control"
/>
</div>

<button type="submit" className="btn btn-dark">
Send
</button>
</form>
)}
{!student && (
<div className="text-center p-3">
<span className="spinner-border spinner-border-sm align-center"></span>
</div>
)}
</div>
);
}

最佳答案

你可以使用 react 钩子(Hook)形式的watch模式来获取每一个变化。

const { register, handleSubmit, reset, formState, watch } = useForm();


useEffect(() => {
watch((value, { name, type }) => console.log(value, name, type));
}, [watch]);

阅读有关 watch 模式表单的更多信息 here

关于reactjs - useEffect 未在 react Hook 表单更改时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73481794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com