简体   繁体   English

为什么在 React.js 中使用 useEffect 钩子时会收到这些警告?

[英]Why I'm getting these warnings while using useEffect hook in React.js?

js and hooks, I have been getting these warnings and I just don't understand why, I did read React documentation but still I don't get it js 和 hooks,我一直收到这些警告,我只是不明白为什么,我确实阅读了 React 文档,但仍然不明白

./src/CustomerList.js Line 32:6: React Hook useEffect has a missing dependency: 'loadData'. ./src/CustomerList.js 第 32:6 行:React Hook useEffect 缺少依赖项:'loadData'。 Either include it or remove the dependency array react-hooks/exhaustive-deps包括它或删除依赖数组 react-hooks/exhaustive-deps

./src/CustomerForm.js Line 44:9: React Hook useEffect has a missing dependency: 'setValue'. ./src/CustomerForm.js Line 44:9:React Hook useEffect 缺少依赖项:'setValue'。 Either include it or remove the dependency array react-hooks/exhaustive-deps包括它或删除依赖数组 react-hooks/exhaustive-deps

I will just paste the hole code side in case the problem is not in the useEffect itself.如果问题不在 useEffect 本身,我将只粘贴孔代码侧。

const CustomerForm = ({customer, saveSuccess}) => {
    const { register, handleSubmit, errors, setValue, reset } = useForm();

    const onSubmit = (data, e) => {
      e.preventDefault();
      if (customer) {
        data.id = customer.id;
        axios.put(BASE_URL, {
            id : data.id,
            firstName : data.firstName,
            lastName : data.lastName,
            phoneNumber:data.phoneNumber,
            email : data.email
        }).then(response => {
            alert("Se actualizó exitosamente.")
        })
    } else {
        axios.post(BASE_URL,  {
            firstName : data.firstName,
            lastName : data.lastName,
            phoneNumber:data.phoneNumber,
            email : data.email
        }).then(response => {
                alert("Se guardó exitosamente.")
            })
    }
    saveSuccess();
    };


    useEffect(() => {
        if (customer) {
            setValue("firstName", customer.firstName);
            setValue("lastName", customer.lastName);
            setValue("phoneNumber", customer.phoneNumber);
            setValue("email", customer.email);
        }
     },[customer]);


    return (
        <form onSubmit={handleSubmit(onSubmit)} noValidate>
          <Input
            name="firstName"
            inputRef={register({ required: true})}
            placeholder="First Name"
            error={!!errors.firstName}
            fullWidth
          />
           <p style={{color: "red"}}>{errors.firstName && "First Name is required"}</p>
           <Input
            name="lastName"
       //     setValue = {customerForm.lastName}
            inputRef={register({ required: true})}
            placeholder="Last Name"
            error={!!errors.lastName}
            fullWidth
          />
           <p style={{color: "red"}}>{errors.lastName && "Last Name is required"}</p>
           <Input
            name="phoneNumber"
         //   setValue = {customerForm.phoneNumber}
            inputRef={register({ required: true})}
            placeholder="Phone Number"
            error={!!errors.phoneNumber}
            fullWidth
          />
           <p style={{color: "red"}}>{errors.phoneNumber && "Phone Number is required"}</p>
           <Input
            name="email"
       //     setValue = {customerForm.email}
            inputRef={register({ required: true})}
            placeholder="Email"
            error={!!errors.email}
            fullWidth
          />
           <p style={{color: "red"}}>{errors.email && "Email is required"}</p>

        <Button
                variant="contained"
                color="default"
                onClick={() => { reset({}) }}
            >
                Reset
                  </Button>
            <Button
                type="submit"
                variant="contained"
                color="primary"
            >
                Save
                  </Button>
      </form>
    );
}

Are you able to link to a working example?你能链接到一个工作示例吗? That might help with debugging, but just by reading over your code it seems those warnings should resolve if you add those dependencies in your useEffect call.这可能有助于调试,但只要通读您的代码,如果您在useEffect调用中添加这些依赖项,这些警告似乎应该会解决。 eg:例如:

/* CustomerForm */

useEffect(() => {
  if (customer) {
    setValue("firstName", customer.firstName);
    setValue("lastName", customer.lastName);
    setValue("phoneNumber", customer.phoneNumber);
    setValue("email", customer.email);
  }
},[customer, loadData, setValue]);

You could add the missing dependency such as您可以添加缺少的依赖项,例如

useEffect(() => {
if (customer) {
        setValue("firstName", customer.firstName);
        setValue("lastName", customer.lastName);
        setValue("phoneNumber", customer.phoneNumber);
        setValue("email", customer.email);
    }
 },[customer,setValue,loadData]);

but in some cases adding a method as a dependency causes an infinite re-render so i think the best way to overcome the warning is to disable it by但在某些情况下,将方法添加为依赖项会导致无限重新渲染,因此我认为克服警告的最佳方法是通过以下方式禁用它

    useEffect(() => {
if (customer) {
        setValue("firstName", customer.firstName);
        setValue("lastName", customer.lastName);
        setValue("phoneNumber", customer.phoneNumber);
        setValue("email", customer.email);
    }
 //eslint-disable-next-line
 },[customer]);

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

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