简体   繁体   English

Useeffect setstate缺少依赖警告

[英]Useeffect setstate missing dependency warning

I've got a question regarding a missing dependency warning.我有一个关于缺少依赖警告的问题。

I've got a GET request where I'd like to set the catch error state.我有一个 GET 请求,我想在其中设置捕获错误 state。 However when setting the error it asks to add the setError in the dependency list.但是,在设置错误时,它会要求在依赖项列表中添加 setError。 The dependency should only be the {value}, not the setError right?依赖项应该只是 {value},而不是 setError 对吗?

useEffect(() => {
    if (value.length === 3) {
      setLoading(true);
      axios
        .get(
          `https://url.com?search=${value}`
        )
        .then((res) => setCompanies(res.data.data))
        .then(() => setLoading(false))
        .catch((err) => {
          if (err.response.status === 500) {
            setError("something went wrong");
          }
        });
    }
  }, [value]);

Warning notification: React Hook useEffect has a missing dependency: 'setError'.警告通知:React Hook useEffect 缺少依赖项:'setError'。 Either include it or remove the dependency array.包括它或删除依赖数组。

you need to declare setError() and error:你需要声明 setError() 和错误:

const [error,setError] = useState('');

useEffect(() => {
    if (value.length === 3) {
      setLoading(true);
      axios
        .get(
          `https://url.com?search=${value}`
        )
        .then((res) => setCompanies(res.data.data))
        .then(() => setLoading(false))
        .catch((err) => {
          if (err.response.status === 500) {
            setError("something went wrong");
          }
        });
    }
  }, [value]);

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

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